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

相关推荐
端平入洛1 小时前
auto有时不auto
c++
郑州光合科技余经理1 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1231 天前
matlab画图工具
开发语言·matlab
dustcell.1 天前
haproxy七层代理
java·开发语言·前端
norlan_jame1 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20211 天前
信号量和信号
linux·c++
多恩Stone1 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054961 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月1 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
蜡笔小马1 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost