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,引入的差异改变了最坏的情况复杂性。

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