排序函数的头文件

版权声明:本文为博主原创文章,转载请务必注明出处和作者,谢谢合作! https://blog.csdn.net/zhanshen112/article/details/83511345

编程中排序函数可以自己写,也可以调用头文件中的库函数。

c编程中如果需要使用排序函数,需要调用<stdlib.h>头文件。排序函数是qsort,也就是快速排序。具体函数语法如下:

#include<stdio.h>
#include<stdlib.h>
int comp(const void*a,const void*b)//用来做比较的函数。
{
    return *(int*)a-*(int*)b;
}
int main()
{
    int a[10] = {2,4,1,5,5,3,7,4,1,5};//乱序的数组。
    int i;
    qsort(a,n,sizeof(int),comp);//调用qsort排序
    for(i=0;i<10;i++)//输出排序后的数组
    {
        printf("%d\t",array[i]);
    }
    return 0;
}

在c++编程中,则是通过调用sort(a,a+n)实现排序。相应头文件是<algorithm>。

#include<stdio.h>
#include<algorithm>
#define N 4
using namespace std;
int main()
{
	int a[N],i;
	for(i=0;i<N;i++)  
    {  
        scanf("%d",&a[i]);  
    }  
	sort(a,a+N);
	for(i=0;i<N;i++)  
    {  
        printf("%d ",a[i]);  
    }  
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/zhanshen112/article/details/83511345