📜  C++中std :: sort()的内部细节

📅  最后修改于: 2021-05-30 14:44:00             🧑  作者: Mango

排序是应用于数据的最基本功能之一。这意味着以特定的方式排列数据,可以增加或减少。 C++ STL中有一个内置函数,名称为sort()。

std :: sort()是C++标准库中的通用函数,用于进行比较排序。

句法:

sort(startaddress, endaddress, comparator)

where:
startaddress: the address of the first element of the array
endaddress: the address of the last element of the array
comparator: the comparison to be done with the array. 
            This argument is optional.

例子:

// C++ program to demonstrate 
// behaviour of sort() in STL. 
  
#include  
using namespace std; 
    
int main() 
{ 
    int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0}; 
    int n = sizeof(arr)/sizeof(arr[0]); 
    
    sort(arr, arr+n); 
    
    cout << "\nArray after sorting using "
         "default sort is : \n"; 
  
    for (int i = 0; i < n; ++i) 
        cout << arr[i] << " "; 
    
    return 0; 
} 
输出:
Array after sorting using default sort is : 
0 1 2 3 4 5 6 7 8 9

时间复杂度

  • 最佳情况– O(N log N)
  • 平均情况-O(N log N)
  • 更差的情况-O(N log N)

其中,N =要排序的元素数。

sort()使用的算法

sort()使用的算法是IntroSort 。 Introsort是一种混合排序算法,它使用三种排序算法来最小化运行时间,即Quicksort,Heapsort和Insertion Sort。简而言之,它是最好的排序算法。它是一种混合排序算法,这意味着它使用多个排序算法作为例程。

/* A Program to sort the array using Introsort.
  The most popular C++ STL Algorithm- sort()
  uses Introsort. */
  
#include
using namespace std;
  
// A utility function to swap the values pointed by
// the two pointers
void swapValue(int *a, int *b)
{
    int *temp = a;
    a = b;
    b = temp;
    return;
}
  
/* Function to sort an array using insertion sort*/
void InsertionSort(int arr[], int *begin, int *end)
{
    // Get the left and the right index of the subarray
    // to be sorted
    int left = begin - arr;
    int right = end - arr;
  
    for (int i = left+1; i <= right; i++)
    {
        int key = arr[i];
        int j = i-1;
  
       /* Move elements of arr[0..i-1], that are
          greater than key, to one position ahead
          of their current position */
        while (j >= left && arr[j] > key)
        {
            arr[j+1] = arr[j];
            j = j-1;
        }
        arr[j+1] = key;
   }
  
   return;
}
  
// A function to parition the array and return
// the partition point
int* Partition(int arr[], int low, int high)
{
    int pivot = arr[high];    // pivot
    int i = (low - 1);  // Index of smaller element
  
    for (int j = low; j <= high- 1; j++)
    {
        // If current element is smaller than or
        // equal to pivot
        if (arr[j] <= pivot)
        {
            // increment index of smaller element
            i++;
  
            swap(arr[i], arr[j]);
        }
    }
    swap(arr[i + 1], arr[high]);
    return (arr + i + 1);
}
  
  
// A function that find the middle of the
// values pointed by the pointers a, b, c
// and return that pointer
int *MedianOfThree(int * a, int * b, int * c)
{
    if (*a < *b && *b < *c)
        return (b);
  
    if (*a < *c && *c <= *b)
        return (c);
  
    if (*b <= *a && *a < *c)
        return (a);
  
    if (*b < *c && *c <= *a)
        return (c);
  
    if (*c <= *a && *a < *b)
        return (a);
  
    if (*c <= *b && *b <= *c)
        return (b);
}
  
// A Utility function to perform intro sort
void IntrosortUtil(int arr[], int * begin,
                  int * end, int depthLimit)
{
    // Count the number of elements
    int size = end - begin;
  
      // If partition size is low then do insertion sort
    if (size < 16)
    {
        InsertionSort(arr, begin, end);
        return;
    }
  
    // If the depth is zero use heapsort
    if (depthLimit == 0)
    {
        make_heap(begin, end+1);
        sort_heap(begin, end+1);
        return;
    }
  
    // Else use a median-of-three concept to
    // find a good pivot
    int * pivot = MedianOfThree(begin, begin+size/2, end);
  
    // Swap the values pointed by the two pointers
    swapValue(pivot, end);
  
   // Perform Quick Sort
    int * partitionPoint = Partition(arr, begin-arr, end-arr);
    IntrosortUtil(arr, begin, partitionPoint-1, depthLimit - 1);
    IntrosortUtil(arr, partitionPoint + 1, end, depthLimit - 1);
  
    return;
}
  
/* Implementation of introsort*/
void Introsort(int arr[], int *begin, int *end)
{
    int depthLimit = 2 * log(end-begin);
  
    // Perform a recursive Introsort
    IntrosortUtil(arr, begin, end, depthLimit);
  
      return;
}
  
// A utility function ot print an array of size n
void printArray(int arr[], int n)
{
   for (int i=0; i < n; i++)
       printf("%d ", arr[i]);
   printf("\n");
}
  
// Driver program to test Introsort
int main()
{
    int arr[] = {3, 1, 23, -9, 233, 23, -313, 32, -9};
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Pass the array, the pointer to the first element and
    // the pointer to the last element
    Introsort(arr, arr, arr+n-1);
    printArray(arr, n);
  
    return(0);
}
输出:
-313 -9 -9 1 3 23 23 32 233

标准C库提供了qsort() ,可用于对数组进行排序。顾名思义,该函数使用QuickSort算法对给定数组进行排序
最好使用sort()而不是qsort(),因为:

  1. sort()不使用像qsort()这样的不安全的void指针。
  2. 相比于快速排序排序()使得大量的函数调用进行比较()函数。
  3. 使用sort()的C++代码相对比使用qsort()的代码更快。

详细文章: sort()与qsort()的比较

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”