C语言---qsort函数

来源:互联网 发布:sql复合主键3个 编辑:程序博客网 时间:2024/06/05 11:29

qsort为C语言提供的快速排序库函数,可对任意类型数组排序

qsort在stdlib.h文件中,其语法格式为

         void qsotr(数组首地址,数组元数个数,数组单个元数类型大小,比较函数名)

比较函数的返回值为int型,形参类型为void *型,eg int cmp(void const *a,void const *b)比较函数的返回值关系到排序的结果,若

             1.a-b 为负数,排序结果为 a在b前

             2.a-b为0      ,排序结果为a,b任意在前

             3.a-b为正数  排序结课为b在a前



#include <stdio.h>

#include<stdlib.h>

int  cmp(void const   *a,void const   *b)

{

      return *(int  *)a-*(int *)b;

}

int main()

{

    int     n;

   scanf("%d" , &n);                         //定义数组元素个数

   int     a[n];

   int     i;

  for(i=0;i<n;i++)

       scanf("%d" , &a[i]);


  qsort(a,n,sizeof(a[0],cmp);


  for(i=0;i<n;i++)

      printf("%d" ,a[i]


   return  0;

}


0 0
原创粉丝点击