sort()

sort ()

sort ()使用时得注明:using namespace std;   或直接打 std::sort()  还得加上  #include <algorithm> 头文件。

    std::sort是一个改进版的qsort. std::sort函数优于qsort的一些特点:对大数组采取9项取样,更完全的三路划分算法,更细致的对不同数组大小采用不同方法排序。sort是qsort的升级版,如果能用sort尽量用sort,使用也比较简单,不像qsort还得自己去写 cmp 函数,只要注明  使用的库函数就可以使用,参数只有两个(如果是普通用法)头指针和尾指针。默认sort排序后是升序,如果想让他降序排列,可以使用自己编的cmp函数。sort(a,b,cmp)第一个参数为数组名,第二个是大小,第三个是比较方式(降序可以选择)。

举例说明

#include<iostream>
#include<algorithm>
using namespace std;
int cmp(int a,int b) {
	if (a > b) {
		return 1;
	}
	else
		return 0;

}
int main() {
	int a[10];
	for (int i = 0; i < 10;i++) {
		cin >> a[i];

	}
	//sort(a,a+10);  升序
  sort(a,a+10,cmp);//降序
	for (int j = 0; j <10;j++) {
		cout << a[j] << endl;


	}
	return 0;
}

参考博客:https://www.cnblogs.com/ForeverJoker/archive/2013/05/25/qsort-sort.html

猜你喜欢

转载自blog.csdn.net/qq_27584277/article/details/82965579