背景
排序是最基礎的算法之一,常見的排序有冒泡排序、選擇排序、插入排序、快速排序等等,其平均時間複雜度由到不等。
然而在做項目或者刷題時,要自己實現一個排序算法相對來說麻煩一些,且有些時候不是很必要。因此,我們可以直接調用C++的庫函數sort()
。
簡介
sort()函數時C++自帶的函數,用於數組的排序。
使用的排序方法是類似於快速排序的方法(既有快速排序又有與其它排序方法的結合),時間複雜度爲,因此效率很快。
用法
頭文件
需引入頭文件:
#include <algorithm>
函數參數
sort()函數共有三個參數:
- 第一個參數表示數組的開始地址;
- 第二個參數表示數組的結束地址;
- 第三個參數表示數組的排序方式(默認爲升序,可自定義排序方式(自己寫一個bool類型的函數))。
舉例說明
- 對數組使用sort()函數,第三個參數爲默認值:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
int array[10] = { 54, 23, 78, 9, 15, 18, 63, 33, 87, 66 };
sort(array, array + 10);
for (int i : array) {
cout << i << " "; //輸出:9 15 18 23 33 54 63 66 78 87
}
system("pause");
return 0;
}
- 對數組使用sort()函數,第三個參數自己構建的函數:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool compare(int a, int b) {
return a > b;
}
int main() {
int array[10] = { 54, 23, 78, 9, 15, 18, 63, 33, 87, 66 };
sort(array, array + 10, compare);
for (int i : array) {
cout << i << " "; //輸出:87 78 66 63 54 33 23 18 15 9
}
system("pause");
return 0;
}
- 對vector數組使用sort()函數,第三個參數爲默認值:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
int array[10] = { 54, 23, 78, 9, 15, 18, 63, 33, 87, 66 };
vector<int>vec(array, array + 10);
sort(vec.begin(), vec.end());
for (int i : vec) {
cout << i << " "; //輸出:9 15 18 23 33 54 63 66 78 87
}
system("pause");
return 0;
}
- 對vector數組使用sort()函數,第三個參數自己構建的函數:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool compare(int a, int b) {
return a > b;
}
int main() {
int array[10] = { 54, 23, 78, 9, 15, 18, 63, 33, 87, 66 };
vector<int>vec(array, array + 10);
sort(vec.begin(), vec.end(), compare);
for (int i : vec) {
cout << i << " "; //輸出:87 78 66 63 54 33 23 18 15 9
}
system("pause");
return 0;
}
參考
https://blog.csdn.net/qq_30587589/article/details/84098333
https://blog.csdn.net/w_linux/article/details/76222112