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

相关推荐
郝学胜-神的一滴8 分钟前
TCP通讯的艺术:从握手到挥手的优雅对话
开发语言·网络·网络协议·tcp/ip·程序人生
黎雁·泠崖9 分钟前
【魔法森林冒险】12/14 场景系统:5大场景的任务串联
java·开发语言
l1t18 分钟前
在python 3.14 容器中安装和使用chdb包
开发语言·python·clickhouse·chdb
梵刹古音19 分钟前
【C++】函数重写
开发语言·c++
Titan202429 分钟前
C++异常学习笔记
c++·笔记·学习
柒儿吖1 小时前
DDlog 高性能异步日志库在 OpenHarmony 的 lycium 适配与分步测试
c++·c#·openharmony
民国二十三画生1 小时前
C++(兼容 C 语言) 的标准输入语法,用来读取一行文本
c语言·开发语言·c++
柒儿吖1 小时前
基于 lycium 在 OpenHarmony 上交叉编译 utfcpp 完整实践
c++·c#·harmonyos
sTone873751 小时前
std::function/模板/裸函数指针选型指南
c++
Codiggerworld1 小时前
从字节码到JVM:深入理解Java的“一次编写,到处运行”魔法
java·开发语言·jvm