标准C库提供qsort函数,可用于对数组进行排序。下面是qsort()函数的原型。
// Sort an array of any type. The parameters are, base // address of array, size of array and pointer to // comparator function void qsort (void* base, size_t num, size_t size, int (*comparator)(const void*, const void*));
它需要一个指向数组的指针、数组中元素的数量、每个元素的大小和一个比较器函数。我们已经详细讨论了qsort比较器 在这里 .
C++标准库提供了类似于STL的函数SoT()。我们讨论了C++排序 在这里 下面是C++ SoTo()函数的原型。
// To sort in default or ascending order. templatevoid sort(T first, T last); // To sort according to the order specified // by comp. template void sort(T first, T last, Compare comp);
平等元素的顺序不能保证得到保留。C++提供了STD::STATELYL排序,可以用来维护订单。
与qsort和sort()的比较 1.实施细节: 顾名思义,qsort函数使用快速排序算法对给定数组进行排序,尽管C标准不要求它实现快速排序。
C++排序函数使用的是一种混合算法。不同的实现使用不同的算法。例如,GNU标准C++库使用3部分混合排序算法:首先执行OnToS排序(自入排序本身是Quasr排序和堆排序的混合),然后对结果进行插入排序。
2.复杂性: C标准没有提到qsort的复杂性。新的C++11标准要求排序的复杂度在最坏的情况下为O(Nlog(N))。C++等03个C++版本允许出现最坏的情况O(n ^ 2)。只要求平均复杂度为O(N logn)。
3.运行时间: STL类的运行速度比C的Q排序快,因为C++的模板为特定的数据类型和特定的比较函数生成优化代码。
STL的排序比手工编码的快速排序快20%-50%,比C qsort库函数快250%-1000%。C可能是最快的语言,但qsort非常慢。
当我们试图对C++ 14的一百万个整数进行排序时,C qStRO()所占用的时间为0.247883秒,而C++的时间(0.086125)仅为0.086125秒。
// C++ program to demonstrate performance of // C qsort and C++ sort() algorithm #include <bits/stdc++.h> using namespace std; // Number of elements to be sorted #define N 1000000 // A comparator function used by qsort int compare( const void * a, const void * b) { return ( *( int *)a - *( int *)b ); } // Driver program to test above functions int main() { int arr[N], dupArr[N]; // seed for random input srand ( time (NULL)); // to measure time taken by qsort and sort clock_t begin, end; double time_spent; // generate random input for ( int i = 0; i < N; i++) dupArr[i] = arr[i] = rand ()%100000; begin = clock (); qsort (arr, N, sizeof ( int ), compare); end = clock (); // calculate time taken by C qsort function time_spent = ( double )(end - begin) / CLOCKS_PER_SEC; cout << "Time taken by C qsort() - " << time_spent << endl; time_spent = 0.0; begin = clock (); sort(dupArr, dupArr + N); end = clock (); // calculate time taken by C++ sort time_spent = ( double )(end - begin) / CLOCKS_PER_SEC; cout << "Time taken by C++ sort() - " << time_spent << endl; return 0; } |
输出:
Time taken by C qsort() - 0.247883 Time taken by C++ sort() - 0.086125
由于内联,C++ SoT()比等效数据快得多。整数容器上的sort()将被编译为使用std::less
4.灵活性: STL的排序适用于所有数据类型,以及不同的数据容器,如C数组、C++向量、C++ DEKE等,以及其他用户可以编写的容器。这种灵活性在C语言中很难实现。
5.安全: 与qsort相比,模板化排序的类型更安全,因为它不像qsort那样需要通过不安全的空指针访问数据项。
参考资料: http://theory.stanford.edu/~amitp/rants/c++-vs-c https://en.wikipedia.org/wiki/Sort_(C%2B%2B)
本文由 阿迪蒂亚·戈尔 .如果你喜欢GeekSforgek,并且想贡献自己的力量,你也可以写一篇文章,并将文章邮寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论