sort()函数
C语言中:
c语言和c++中,对于sort函数的使用,不同。c语言中没有预置的sort函数,如果在c语言中,要调用sort函数,就需要自定义一个用于排序的函数,或者使用c语言自有的qsort函数,其头文件为stdlib.h。
void sort(int *a, int l) //a为数组地址,l为数组长度。
{
int i, j;
int v;
//排序主体
for(i = 0; i < l - 1; i ++)
for(j = i+1; j < l; j ++)
{
if(a[i] > a[j])//如前面的比后面的大,则交换。
{
v = a[i];
a[i] = a[j];
a[j] = v;
}
}
}
C++语言中:
#include<algorithm>
using namespace std;
sort(first_pointer,first_pointer+n,cmp);
形式:
sort(first_pointer,first_pointer+n,cmp);
参数解释:
first_pointer: 写数组的首地址【一般写数组名即可】。
first_pointer+n: 写首地址+数组长度n。
cmp: 写比较函数的名称【自定义函数cmp】,如果第三个参数不写,则sort默认按数组升序排序。
例子:
int A[100];
bool cmp(int a,int b)//int为数组数据类型
{
return a>b;//降序排列
}
sort(A,A+100,cmp);