vector+算法sort与list+sort的效率比较,容易写错的地方原因探析

我写的代码:

cpp 复制代码
#include <iostream>
using namespace std;
#include <vector>
#include <list>
#include <algorithm>
int main()
{
	const int N = 10000000;
	vector<int> v;
	list<int> l;
	for (int i = 0; i < N; i++)
	{
		v.push_back(i);
		l.push_back(i);
	}

	int begin1 = clock();
	sort(v.begin(), v.end());
	int end1 = clock();

	int begin2 = clock();
	l.sort();
	int end2 = clock();

	cout << "vector+算法:" << end1 - begin1 << endl;
	cout << "list+sort:" << end2 - begin2 << endl;
}

运行结果:无论N为多大,上面永远大于下面

老师的代码:

cpp 复制代码
#include <time.h>
#include <iostream>
using namespace std;
#include <list>
#include <vector>
#include <algorithm>
 
int main()
{
	srand(time(0));
	const int N = 10000000;
	vector<int> v;
	v.reserve(N);
 
	list<int> lt2;
 
	for (int i = 0; i < N; i++)
	{
		auto e = rand();
		v.push_back(e);
		lt2.push_back(e);
	}
 
	int begin1 = clock();
	sort(v.begin(), v.end());
	int end1 = clock();
 
	int begin2 = clock();
	lt2.sort();
	int end2 = clock();
 
	cout << "vector sort:" << end1 - begin1 << endl;
	cout << "list sort:" << end2 - begin2 << endl;
}

运行结果:N较小时,差不多大,N较大时,上面比小面小得多

原因:

快排在最坏情况下的时间复杂度为(n^2),最坏情况对应的是数据有序,我写的代码就是有序数,所有跑出来的结果和老师的无序数相反,快排的平均时间复杂度是(nlgn),快排只有在无序数中排序才有意义

相关推荐
樱木Plus2 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
blasit4 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_5 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星5 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛7 天前
delete又未完全delete
c++
端平入洛8 天前
auto有时不auto
c++
郑州光合科技余经理8 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1238 天前
matlab画图工具
开发语言·matlab
dustcell.8 天前
haproxy七层代理
java·开发语言·前端
norlan_jame9 天前
C-PHY与D-PHY差异
c语言·开发语言