sort函式對陣列和字串的排序

2021-07-12 03:10:07 字數 2317 閱讀 3857

(一)為什麼要用c++標準庫里的排序函式

sort()函式是c++一種排序方法之一,它使用的排序方法是類似於快排的方法,時間複雜度為n*log2(n),執行效率較高!

(二)c++標準庫里的排序函式的使用方法

(1)sort函式包含在標頭檔案為 #include」algorithm」 的c++標準庫中,呼叫標準庫里的排序方法可以不必知道其內部是如何實現的,只要出現我們想要的結果即可!

(2)sort函式有三個引數:

1.第乙個是要排序的陣列的起始位址。

2.第二個是結束的位址(最後一位要排序的位址)。

3.第三個引數是排序的方法,可以是從小到大也可是從大到小,還可以不寫第三個引數,此時預設的排序方法是從小到大排序。

sort函式使用模板:

sort(start,end,排序方法)

下面就具體使用sort函式結合對陣列裡的十個數進行排序做乙個說明!

例一:sort函式沒有第三個引數,實現的是從小到大

#include 

#include

using

namespace

std;

int main()

; cout

<< "排序前順序: ";

for (int i = 0;i < 10;i++)

cout

<< endl;

sort(arr, arr + 10);

cout

<< "排序後順序: ";

for (int i = 0;i < 10;i++)

cout

<< endl;

return

0;}

例二:設定第三個引數,實現從大到小的排序

通過上面的例子,會產生疑問:要實現從大到小的排序怎麼辦?這就如前文所說需要在sort函式裡的第三個引數裡做文章了,告訴程式我要從大到小排序!需要加入乙個比較函式compare,此函式的實現過程是這樣的。

bool compare(int a, int b)      //定義排序規則

這就是告訴程式要實現從大到小的排序的方法!

#include 

#include

using

namespace

std;

bool compare(int a, int b) //定義排序規則

int main()

; cout

<< "排序前順序: ";

for (int i = 0;i < 10;i++)

cout

<< endl;

sort(arr, arr + 10,compare);

cout

<< "排序後順序: ";

for (int i = 0;i < 10;i++)

cout

<< endl;

return

0;}

例三:利用sort函式對字串從小到大排序

#include 

#include

using

namespace

std;

int main()

cout

<< endl;

sort(str, str+ 9);

cout

<< "排序後順序: ";

for (int i = 0;i < 9;i++)

cout

<< endl;

return

0;}

輸出結果:

例四:利用sort函式對字串從大到小排序

#include 

#include

using

namespace

std;

bool compare(char a, char b) //新增排序規則

int main()

cout

<< endl;

sort(str, str+ 9,compare); //呼叫排序規則

cout

<< "排序後順序: ";

for (int i = 0;i < 9;i++)

cout

<< endl;

return

0;}

使用Array的Sort 方法對陣列進行排序

來看看排序吧 using system using system.collections.generic using system.text namespace ljun csharp study 排序前的陣列 console.writeline 陣列排序前為 foreach int number ...

有關字元陣列和字串的函式

字串可以用字元陣列與字串變數兩種方式來儲存,效果類似。一 用字元陣列來儲存字串 char st1 100 st2 100 字元陣列說明 cin st1 st2 long a,b 輸入 hello,world 則st1 st2 字元 0 為字串結束標誌 1.字元陣列長度 strlen st1 如a s...

Linux awk和sort處理字串

題目 有乙個檔案b.txt 要求將網域名稱擷取出來,並且統計出重複網域名稱出現的次數 如下 awk f b.txt sort uniq c 講解 awk的基本用法 格式 awk 動作 檔名 示例 awk demo.txt f 引數,指定分隔符,單引號中是指定的分割字段 awk f 0 代表的是一整行...