顾名思义,sort就是用来排序的函数,它根据具体情形使用不同的排序方法,效率较高。一般来说,不推荐使用C语言中的qsort函数,原因是qsort用起来比较烦琐,涉及很多指针的操作。而且sort在实现中规避了经典快速排序中可能出现的会导致实际复杂度退化到(o(n2)的极端情况。希望读者能通过这篇介绍来轻松愉快地使用sort函数。
1.如何使用sort排序
sort函数的使用必须加上头文件“#include<algorithm>”和“using namespace std;”,其使用的方式如下:
sort(首元素地址(必填),尾元素地址的下一个地址(必填),比较函数(非必填));
可以看到,sort的参数有三个,其中前两个是必填的,而比较函数则可以根据需要填写,如果不写比较函数,则默认对前面给出的区间进行递增排序。
[C++] 纯文本查看 复制代码 #include <stdio.h>
#include <algorithm>
using namespace std;
int main(){
int a[6] = {9,4,2,5,6,-1};
sort(a,a+4);
//a[0]~a[3]从小到大排序
for(int i=0;i<6;i++){
printf("%d",a[i]);
}
printf("\n");
//a[0]~a[5]从小到大排序
sort(a,a+6);
for(int i=0;i<6;i++){
printf("%d",a[i]);
}
return 0;
}
运行之后可以得到下面的结果,可以试着理解一下(特别注意理解“尾元素地址的下一个地址”)。输出结果:
[CSS] 纯文本查看 复制代码 24596-1
-124569
又如,对double型数组排序:
[C++] 纯文本查看 复制代码 #include <stdio.h>
#include <algorithm>
using namespace std;
int main(){
double a[] = {1.1,-1.1,99};
sort(a,a+3);
for(int i=0;i<3;i++){
printf("%.1f",a[i]);
}
return 0;
}
输出结果:
[AppleScript] 纯文本查看 复制代码 -1.1 1.1 99.0
再如,对char数组排序(默认为字典序)
[C++] 纯文本查看 复制代码 #include <stdio.h>
#include <algorithm>
using namespace std;
int main(){
char c[]={'I','L','O','V','E','U'};
sort(c,c+6);
for(int i=0;i<6;i++){
printf("%c",c[i]);
}
return 0;
}
输出结果:
[AppleScript] 纯文本查看 复制代码 EILOUV
|