學演算法的第一天你在學冒泡、桶排
在你還沒搞明白快排和歸併的時候
你已經學到了資料結構最後的堆排序和希爾排序
可以說排序是很多競賽生的噩夢……
於是它誕生了
void std::sort()
Sort the elements of a sequence using a predicate for comparison.
引數:
__first – An iterator.
__last – Another iterator.
__comp – A comparison functor.
針對一個地址區間完成排序,演算法每次自動選擇,以快排為主
C++需要標頭檔案#include <algorithm>
(當然萬能頭我也沒意見)
最簡單的就是用它完成int型別升序排序
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a[5] = {2, 1, 3, 5, 4};
sort(a, a + 5);
for (int i = 0; i < 5; i++) cout << a[i] << " ";
}
輸出如下,很簡單
1 2 3 4 5
這裡傳入給sort的引數 a
和 a + 5
都是地址,和大多數程式語言一樣,這裡遵循左閉右開原則,即函式實際會讀取和操作的五個地址如下:
a + 0
a + 1
a + 2
a + 3
a + 4
如果需要降序排序,程式如下
#include <iostream>
#include <algorithm>
using namespace std;
bool cmp(int x, int y){
return x > y;
}
int main() {
int a[5] = {2, 1, 3, 5, 4};
sort(a, a + 5, cmp);
for (int i = 0; i < 5; i++) cout << a[i] << " ";
}
輸出
5 4 3 2 1
我們多寫了一個bool型別的cmp函式,並將其地址作為第3個引數傳給了sort
cmp可以替換其內建的函式來判斷究竟該讓哪些元素在前哪些元素在後
很多小夥伴可能有個疑惑:如何從實質上理解cmp函式,或者說我究竟該怎麼記住cmp怎麼寫呢?
我們來看這三個點:
- 毋庸置疑,cmp函式返回bool型別,表示當前排序是否正確(具體見3)
- cmp函式應接受兩個引數,型別與要排序的陣列相同(可以是int、short和long long這些常見型別,當然也可以是結構體)
- cmp返回值的實際意義是傳入a、b兩個引數,a在前b在後的排序是否是正確的,若是正確的返回1(true),否則返回0(false)
那麼我們再看一個結構體的排序例項:輸入10個學生的名字和成績,按照成績從高到低排序後輸出
輸入資料:
Yixiangzhilv 90
Mydr 60
Xiaoming 10
Mr.Glass 60
GZN 80
Wangzi 85
Hyx 100
Wyx 99
Xth 0
Zz 75
程式實現如下
#include <algorithm>
#include <iostream>
using namespace std;
struct node {
string name;
int score;
};
bool cmp(struct node x, struct node y) {
return x.score > y.score;
}
int main() {
struct node a[10];
for (int i = 0; i < 10; i++) cin >> a[i].name >> a[i].score;
sort(a, a + 10, cmp);
for (int i = 0; i < 10; i++) cout << a[i].name << " " << a[i].score << endl;
}
(此處還有一個C++知識:如果已經定義結構體node,那麼 struct node a[10];
和 node a[10];
都是合法的)