【C++基础编程】 #026 sort()函数简介

背景

排序是最基础的算法之一,常见的排序有冒泡排序、选择排序、插入排序、快速排序等等,其平均时间复杂度由 O ( n 2 ) O(n^2) O ( n l o g 2 n ) O(nlog_2n) 不等。

然而在做项目或者刷题时,要自己实现一个排序算法相对来说麻烦一些,且有些时候不是很必要。因此,我们可以直接调用C++的库函数sort()

简介

sort()函数时C++自带的函数,用于数组的排序。

使用的排序方法是类似于快速排序的方法(既有快速排序又有与其它排序方法的结合),时间复杂度为 O ( n l o g 2 n ) O(nlog_2n) ,因此效率很快。

用法

头文件

需引入头文件:
#include <algorithm>

函数参数

sort()函数共有三个参数:

  1. 第一个参数表示数组的开始地址
  2. 第二个参数表示数组的结束地址
  3. 第三个参数表示数组的排序方式(默认为升序,可自定义排序方式(自己写一个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

猜你喜欢

转载自blog.csdn.net/qq_39856931/article/details/106758276
今日推荐