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),快排只有在无序数中排序才有意义

相关推荐
Mr__Miss3 分钟前
面试踩过的坑
java·开发语言
啊丢_5 分钟前
C++——Lambda表达式
开发语言·c++
Chh07151 小时前
《R语言SCI期刊论文绘图专题计划》大纲
开发语言·r语言
Yeats_Liao1 小时前
Go 语言 TCP 端口扫描器实现与 Goroutine 池原理
开发语言·tcp/ip·golang
Wendy_robot1 小时前
【滑动窗口+哈希表/数组记录】Leetcode 438. 找到字符串中所有字母异位词
c++·算法·leetcode
Thomas_YXQ1 小时前
Unity3D IK解算器技术分析
开发语言·搜索引擎·unity·全文检索·unity3d·lucene
liuweidong08022 小时前
【Pandas】pandas DataFrame rsub
开发语言·python·pandas
转基因2 小时前
Codeforces Round 1020 (Div. 3)(题解ABCDEF)
数据结构·c++·算法
whoarethenext2 小时前
c++的jsoncpp使用
开发语言·c++·jsoncpp
niuTaylor2 小时前
Linux驱动开发快速上手指南:从理论到实战
linux·运维·开发语言·驱动开发·c#