📜  C qsort()与C++ sort()

📅  最后修改于: 2021-04-27 22:56:19             🧑  作者: Mango

标准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++标准库提供了一个类似的函数sort(),该函数起源于STL。我们在这里讨论了C++排序。以下是C++ sort()函数的原型。

// To sort in default or ascending order.
template 
void 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 :: stable_sort。

与qsort和sort()的比较
1.实施细节:
顾名思义,尽管C标准不要求qsort函数Quicksort,但qsort函数使用QuickSort算法对给定的数组进行排序。

C++排序函数使用了introsort,它是一种混合算法。不同的实现使用不同的算法。例如,GNU Standard C++库使用三部分混合排序算法:首先执行introsort(introsort本身是quicksort和堆排序的混合),然后对结果进行插入排序。

2.复杂性:
C标准没有谈论qsort的复杂性。新的C++ 11标准要求在最坏的情况下排序的复杂度为O(Nlog(N))。诸如C++ 03之类的C++早期版本允许O(N ^ 2)的最坏情况。仅要求平均复杂度为O(N log N)。

3.运行时间:
STL的排序比C的qsort快,因为C++的模板针对特定的数据类型和特定的比较函数生成优化的代码。

STL的排序比手动编码的quicksort快20%到50%,比C qsort库函数快250%到1000%。 C可能是最快的语言,但是qsort非常慢。

当我们尝试在C++ 14上对一百万个整数进行排序时,C qsort()花费的时间为0.247883秒,而C++ sort()花费的时间仅为0.086125秒

// C++ program to demonstrate performance of
// C qsort and C++ sort() algorithm
#include 
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