[STL source code analysis] Is list::sort really easy to use? Centos7-Linux environment g++Release vector array sorting and list sorting efficiency test [super detailed comments and explanations]

 


what was said before

When using some containers of the standard template library of C++, we will inevitably encounter the problem of ordering the sequence.

When learning lists, we may learn that algorithm::sort is not a panacea.

When we want to sort a list , we may use list::sort .

Today, let's discuss whether it is more efficient to use vector+algorithm::sort or list+list::sort to sort a bunch of data !

foreword

那么这里博主先安利一下一些干货满满的专栏啦!

手撕数据结构https://blog.csdn.net/yu_cblog/category_11490888.html?spm=1001.2014.3001.5482这里包含了博主很多的数据结构学习上的总结,每一篇都是超级用心编写的,有兴趣的伙伴们都支持一下吧!
算法专栏https://blog.csdn.net/yu_cblog/category_11464817.html这里是STL源码剖析专栏,这个专栏将会持续更新STL各种容器的模拟实现。

STL源码剖析https://blog.csdn.net/yu_cblog/category_11983210.html?spm=1001.2014.3001.5482


Efficiency Analysis of Two Sorting Bottom Sorting Algorithms

algorithm::sort uses quicksort and its optimization

list::sort uses merge sort (because the chained storage structure merge is a constant-level space complexity)

After learning the sorting algorithm, we can understand that the average time complexity of merge sort and quick sort is O(nlogn), and they both belong to the same level of sorting algorithms.

Now let's test the efficiency comparison between VS and g++ environment respectively.

test code

//现在有n(很大)个数据需要排序,哪一种好?
//1.vector+algorithm::sort
//2.list+list::sort
//写个程序来看一下,用release跑
//vector快
//当大量数据需要访问的时候,vector的随机访问性的优势就能体现出来了
void TestOP() {
	srand(time(0));
	const int N = 10000000;
	vector<int>v;
	v.reserve(N);
	list<int>lt1;
	list<int>lt2;
	for (int i = 0; i < N; i++) {
		auto e = rand();
		v.push_back(e);
		lt2.push_back(e);
	}
	//拷贝到vector排序,排完之后再拷贝回来
	int begin1 = clock();
	sort(v.begin(), v.end());
	int end1 = clock();

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

	cout << "vectorSort" << " " << end1 - begin1 << endl;
	cout << "listSort" << " " << end2 - begin2 << endl;
}
int main() {
	TestOP();
	return 0;
}

Test Results

In the VS environment:

Result in g++ environment:

result:

Obviously, using vector is more efficient.

Why is this?

We all know that the bottom layer of vector is a sequence table, that is, an array. Arrays have random access, which is not available in linked lists. Therefore, when we have a large amount of data to be accessed and manipulated, the advantages of vector are reflected!

In fact, list::sort is rarely used basically.

end

If you feel that this article is helpful to you, don't forget to click three links! Your support is my greatest motivation!

For more articles please visit my homepage

@Backpack https://blog.csdn.net/Yu_Cblog?spm=1000.2115.3001.5343

Guess you like

Origin blog.csdn.net/Yu_Cblog/article/details/127045111