C++ STL 中的 std::sort()


sort() 是  C ++ STL 中內置函數。此函數內部使用快速排序實現,故它的復雜性是O(Nlog(N))

sort 函數原型為

sort(startaddress, endaddress)

startaddress: 參加排序的第一個元素的地址
endaddress: 參加排序的最后一個元素的下一個連續元素的地址。
實際上sort()在[startaddress,endaddress)的范圍內排序

 

#include <iostream> 
#include <algorithm> 
  
using namespace std; 
  
void show(int a[]) 
{ 
    for(int i = 0; i < 10; ++i) 
        cout << a[i] << " "; 
} 
  
int main() 
{ 
    int a[10]= {1, 5, 8, 9, 6, 7, 3, 4, 2, 0}; 
    cout << "\n 排序前數組為 : "; 
    show(a); 
  
    sort(a, a+10); 
  
    cout << "\n\n 排序后數組為 : "; 
    show(a); 
  
    return 0; 
  
} 

上面程序運行結果為:

 排序前數組為 : 1 5 8 9 6 7 3 4 2 0

 排序后數組為 : 0 1 2 3 4 5 6 7 8 9

默認情況下,sort()按升序對數組進行排序。

如何按降序排序?

sort()接受第三個參數,用於指定元素的排序順序。我們可以傳遞“greater()”函數來按降序排序。

#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0}; 
    int n = sizeof(arr)/sizeof(arr[0]); 
  
    sort(arr, arr+n, greater<int>()); 
  
    cout << " 排序后數組為 : \n"; 
    for (int i = 0; i < n; ++i) 
        cout << arr[i] << " "; 
  
    return 0; 
} 

 上面程序運行結果為:

 排序后數組為 :
9 8 7 6 5 4 3 2 1 0

 如何按特定順序排序?

我們也可以編寫自己的比較器函數並將其作為第三個參數傳遞。

#include<bits/stdc++.h> 
using namespace std; 
  
// 一個時間間隔包括開始時間 start 和結束時間 end
struct Interval 
{ 
    int start, end; 
}; 
  
// 自定義比較函數以時間間隔的升序排序
bool compareInterval(Interval i1, Interval i2) 
{ 
    return (i1.start < i2.start); 
} 
  
int main() 
{ 
    Interval arr[] =  { {6,8}, {1,9}, {2,4}, {4,7} }; 
    int n = sizeof(arr)/sizeof(arr[0]); 
  
   
    sort(arr, arr+n, compareInterval); 
  
    cout << "時間間隔數組以開始時間升序排序后結果為 : \n"; 
    for (int i=0; i<n; i++) 
       cout << "[" << arr[i].start << "," << arr[i].end 
            << "] "; 
  
    return 0; 
} 

 

 上面程序運行結果為:

時間間隔數組以開始時間升序排序后結果為 :
[1,9] [2,4] [4,7] [6,8]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM