C 中的sort排序用法

2021-10-02 13:52:03 字數 2565 閱讀 9289

c中的qsort()採用的是快排演算法,c++的sort()則是改進的快排演算法。兩者的時間複雜度都是n*(logn),但是實際應用中,sort()一般要快些,建議使用sort()。

stl中就自帶了排序函式sort對給定區間所有元素進行排序 要使用此函式只需用

#include sort即可使用,語法描述為:

sort(begin,end),表示乙個範圍,用法示例:

#include

#include

using namespace std;

intmain()

,i;sort

(a,a+10)

;for

(i=0

;i<

10;i++

) cout<

}

輸出顯示:

123

4455

679--

----

----

----

----

----

----

----

--process exited after 0.4222 seconds with return value 0

請按任意鍵繼續.

..

輸出結果將是把陣列a按公升序排序;

如果想將其按照降序排序,即需自己定義乙個比較函式:

用法示例:

bool

cmp(

int a,

int b)

#include

#include

using

namespace std;

bool

cmp(

int a,

int b)

intmain()

,i;sort

(a,a+

10,cmp)

;for

(i=0

;i<

10;i++

) cout<

}

輸出結果:

976

5544

321--

----

----

----

----

----

----

----

--process exited after 2.921 seconds with return value 0

請按任意鍵繼續.

..

對浮點型資料也是一樣,用法示例:

#include

#include

#include

using

namespace std;

bool

cmp(

double a,

double b)

intmain()

;int i;

sort

(a,a+

10,cmp)

; cout

);for(i=

0;i<

10;i++

) cout<

}

輸出結果:

9.00

7.00

6.00

5.00

5.00

4.00

4.00

3.00

2.00

1.00

----

----

----

----

----

----

----

----

process exited after 0.2294 seconds with return value 0

請按任意鍵繼續.

..

還可以按照結構體排序:

#include

#include

#include

using

namespace std;

struct link

;bool

cmp(link x,link y)

intmain()

輸出結果:

9.00

7.00

6.00

5.00

5.00

4.00

4.00

3.00

2.00

1.00

----

----

----

----

----

----

----

----

process exited after 0.2294 seconds with return value 0

請按任意鍵繼續.

..

C 中List的排序用法 Sort

要對自定義類陣列或list進行排序,譬如 listuserlist arraylist arraylist 最重要的是 繼承icomparer介面,實現int icomparer.compare t t1,t t2 方法。如下 繼承icomparer介面,實現同一自定義型別 物件比較 t為泛用型別 ...

C 中的sort 排序函式用法

原文章 中的sort 排序函式用法m p 10183210.html sort first pointer,first pointer n,cmp 該函式可以給陣列,或者鍊錶list 向量排序。實現原理 sort並不是簡單的快速排序,它對普通的快速排序進行了優化,此外,它還結合了插入排序和推排序。系...

C 中sort 排序函式的用法

sort first pointer,first pointer n,cmp 該函式可以給陣列,或者鍊錶list 向量排序。實現原理 sort並不是簡單的快速排序,它對普通的快速排序進行了優化,此外,它還結合了插入排序和推排序。系統會根據你的資料形式和資料量自動選擇合適的排序方法,這並不是說它每次排...