qsort排序函数
qsort函数是C语言编译器函数库自带的排序函数。它是ANSI C标准中提供的,其声明在stdlib.h文件中,是根据二分法写的,其时间复杂度为n*log(n)
qsort要求提供一个自己定义的比较函数。比较函数使得qsort通用性更好,有了比较函数qsort可以实现对数组、字符串、结构体等结构进行升序或降序排序。
例如比较函数 int cmp(const void *a, const void *b) 中有两个元素作为参数(参数的格式不能变),返回一个int值,比较函数cmp的作用就是给qsort指明元素的大小是怎么比较的。
以int类型为例
int num[100];
int cmp_int(const void* a, const void* b) //参数格式固定
{
return *(int *)a - *(int *)b;
}
qsort(num, 100, sizeof(num[0]), cmp_int);
可见,参数列表是两个空指针,现在他要去指向你的数组元素。所以转换为你当前的类型,然后取值。默认升序排列(从小到大),如果想降序排列返回*b-*a即可。
Sort排序函数
sort(begin, end, cmp),其中begin为指向待sort()的数组的第一个元素的指针,end为指向待sort()的数组的最后一个元素的下一个位置的指针,cmp参数为排序准则,如果没有的话,默认以非降序排序。
bool cmp(int x,int y)
{
return x >y;
}
//sort默认为非降序排序
int main()
{
vector<int>a{2,5,1,4,6};
//正向排序
sort(a.begin(),a.end());
for(auto i:a)
{
cout<<i<<" ";
}
cout<<endl;
//反向排序
sort(a.rbegin(),a.rend());
for(auto i:a)
{
cout<<i<<" ";
}
cout<<endl;
//带cmp参数的排序
sort(a.begin(),a.end(),cmp);
for(auto i:a)
{
cout<<i<<" ";
}
cout<<endl;
}
结果
1 2 4 5 6
6 5 4 2 1
6 5 4 2 1