C++ STL的sort函數 排序

STL的sort基於快速排序,是一種複雜度爲 O(nlogn)高效排序方法。

但sort屬於不穩定排序

頭文件:#include< algorithm > 或 #include<bits/stdc++.h> //萬能頭文件

函數: sort( first, end, compare )

數據範圍:[ first, end ) ,不包含 end

參數:
第一個參數:要排序數組的起始地址
第二個參數:要排序數組的最後一個數據的下一個地址
第三個參數:可有可無,是一個 bool 型函數,定義的是排序方法。不填寫時,sort 默認按從小到大排序

bool compare(int x, int y){  //填寫該函數時,sort 爲從大到小排序
	return x > y;
}

示例:

#include<bits/stdc++.h>

using namespace std;

bool compare(int x, int y){
	return x > y;
}

int main(){
	int a[10]={5, 8, 9, 0, 4, 1, 3, 7, 6, 2};
	
	sort(a, a+10);            //從小到大排序
	for(int i=0; i<10; i++){
		cout << a[i] << ' ';
	}                         //結果:0 1 2 3 4 5 6 7 8 9
	
	cout << endl << endl;
	
	sort(a, a+10, compare);   //從大到小排序
	for(int i=0; i<10; i++){
		cout << a[i] << ' ';
	}                         //結果:9 8 7 6 5 4 3 2 1 0
	
	return 0;
}

結果:
在這裏插入圖片描述

C++ Reference解釋:

詳情請轉 std::sort

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章