C++排序算法

數組排序

#include <algorithm>
static const size_t v_size = 2000;
int v[v_size];
// Fill the array by values
std::sort(v,v+v_size); 

或者

#include <algorithm>
int main(){
  int v[2000];
  std::sort(std::begin(v), std::end(v));
}

vector排序

int main() 
{ 
    vector<int> v{ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; 
  
    sort(v.begin(), v.end()); 
  
    cout << "Sorted \n"; 
    for (auto x : v) 
        cout << x << " "; 
  
    return 0; 
} 

遞減排序

#include <algorithm>
int main(){
    vector<int> v{1, 5, 8, 9, 6, 7, 3, 4, 2, 0};
    sort(v.begin(), v.end(),greater<int>());
}

自定義排序規則

using namespace std; 
  
// An interval has start time and end time 
struct Interval { 
    int start, end; 
}; 
  
// Compares two intervals according to staring times. 
bool compareInterval(Interval i1, Interval i2) 
{ 
    return (i1.start < i2.start); 
} 
  
int main() 
{ 
    vector<Interval> v { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } }; 
  
    // sort the intervals in increasing order of 
    // start time 
    sort(v.begin(), v.end(), compareInterval); 
  
    cout << "Intervals sorted by start time : \n"; 
    for (auto x : v) 
        cout << "[" << x.start << ", " << x.end << "] "; 
  
    return 0; 
} 

sort的內部實現

C標準沒有談及它的qsort的複雜性。新的C ++ 11標準要求在最壞的情況下排序的複雜性爲O(Nlog(N))。早期版本的C ++(如C ++ 03)允許O(N ^ 2)的最壞情況。只需要平均複雜度爲O(N log N)。
STL的排序是IntroSort。IntroSort本質上是一個QuickSort,引入的差異改變了最壞的情況複雜性。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章