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

相关推荐
quantdash_cc几秒前
Python 获取实时行情后如何进行批量筛选?从全市场快照到策略候选池
开发语言·python·数据分析·量化交易·股票数据·quantdash
cu1436 分钟前
细谈GM8229的具体功能与其应用
c语言·c++·人工智能·单片机
论文复现现场10 分钟前
论文复现看到“RTX 3090 or higher”:显存、CUDA、batch size 与 OOM 怎么判断?
开发语言·pytorch·batch·cuda·rtx3090
智鸟科技GemeOpen开发者智能设备12 分钟前
GemeOpen 智能音箱 GSSM0B - 播放控制(Java示例)
java·开发语言·智能音箱
qq_406981031 小时前
c++构造函数初始化列表
c++
m0_380743871 小时前
PHP 8.3 接口返回数据为空怎么排查
开发语言·php
谢亮_vipxieliang1 小时前
Java 21 新特性实战:Record、Sealed、模式匹配
java·开发语言
王老师青少年编程1 小时前
2026年9月GESP真题及题解(C++八级):末班车
c++·题解·真题·gesp·八级·2026年9月·末班车
霸道流氓气质1 小时前
LLM 应用限流与熔断机制完全指南:从多层防护架构到Java生产级弹性实战
java·开发语言·架构
大侠归来1 小时前
C语言内存管理:从栈到堆的完整指南
c语言·开发语言·python