STL排序方法( 轉)

2021-06-16 03:49:35 字數 1996 閱讀 7257

//適合讀者:stl初學者

//#include

//快速排序sort()  (平均o(nlogn) 

//穩定排序stable_sort() (最好o(nlogn),最壞o(n(logn)^2) 用法與sort()相同

//堆排序s ort_heap()  (o(nlogn)) 用法同sort(),要先make_heap()或push_heap()

/************目錄************

用法一:內建型別的由小到大排序:使用預設比較函式(less())

sort(a,a+len); //a:陣列名,len:陣列長度=sizeof(arrray)/sizeof(*array)

用法二:內建型別的由大到小排序:使用內建比較函式(greater())

sort(a,a+len,greater()); //greater():#include

用法三:自定義型別物件陣列的由大到小排序:使用游離比較函式(mygreater(type&, type&)

bool mygreater(const type& a, const type& b)

sort(a,a+len,mygreater); //自定義型別物件陣列的由大到小排序

堆排序版本:

bool mygreater(const type& a, const type& b)

make_heap(a,a+len,mygreater);

sort_heap(a,a+len,mygreater); //引數必須完全一樣!

用法四:指標陣列的由大到小排序:使用游離比較函式(mygreater(const type*, const type*)

bool mygreater(const int* a, const int* b)

sort(p,p+len,mygreater); //指標陣列的由大到小排序,適用於索引排序

/**/

//***********例子************

#include

#include

#include

using namespace std;

//用法一:內建型別的由小到大排序:使用預設比較函式(less())

/*void main()

;int len=sizeof(a)/sizeof(int);

sort(a,a+len); //預設:內建型別的由小到大排序

for (int i=0; i())

/*void main()

;int len=sizeof(a)/sizeof(int);

sort(a,a+len,greater()); //內建型別的由大到小排序

for (int i=0; ib;}

void main()

;int len=sizeof(a)/sizeof(int);

sort(a,a+len,mygreater); //自定義型別的由大到小排序

for (int i=0; ib;}

void main()

;int len=sizeof(a)/sizeof(int);

make_heap(a,a+len,mygreater);

sort_heap(a,a+len,mygreater); //自定義型別的由大到小排序

for (int i=0; i//用法四:自定義型別指標陣列的由大到小排序:使用游離比較函式(mygreater(type&, type&)

/*bool mygreater(int* a, int* b)

void main()

;int* p[5];

for(int i=0;i<5;i++) p[i]=&a[i];

int len=sizeof(a)/sizeof(int);

sort(p,p+len,mygreater); //自定義型別的由大到小排序

for (i=0; icout

cout<}/**/

STL排序方法

適合讀者 stl初學者 include 快速排序sort 平均o nlogn 穩定排序stable sort 最好o nlogn 最壞o n logn 2 用法與sort 相同 堆排序s ort heap o nlogn 用法同sort 要先make heap 或push heap 目錄 用法一 內...

STL 穩定排序

演算法流程如下圖 主要使用的就是類似歸併排序,分為有快取和沒有快取兩種情況,其中快取的大小也影響程式的遞迴呼叫。源 如下 template bidirectionaliterator1 rotate adaptive bidirectionaliterator1 first,bidirectiona...

兩種排序方法(字串 排序 STL)

時間限制 1秒 空間限制 32768k 熱度指數 12801 考拉有n個字串字串,任意兩個字串長度都是不同的。考拉最近學習到有兩種字串的排序方法 1.根據字串的字典序排序。例如 car carriage cats doggies koala 2.根據字串的長度排序。例如 car cats koala...