函数原型:void qsort(void *base, int nelem, int width, int(*fcmp)(const void*, const *))
头文件:#include<stdlib.h>
是否是标准函数:是
函数功能:对记录进行从小到大的快速排序。参数base指向存放待排序列的数组的首地址,nelem为数组中元素的个数,width为每个元素的字节数,int(*fcmp)(const void *, const *)为由用户提供的比较函数。
返回值:无
例程如下:利用qsort函数对无序序列进行快速排序(从小到大排序)。
#include <stdio.h>
#include <stdlib.h>
int CMP ( const void *a , const void *b )
{ return *(int *)b - *(int *)a; }
int main(void)
{
int sort[10]={3,2,6,12,1,7,-5,9,30,16} ;
int i;
printf("\nThe array that is before sort\n");
for(i=0;i<10;i++)
printf("%d ",sort[i]);
qsort(sort,10,sizeof(int),CMP) ;
printf("\nThe array that is after sort\n");
for(i=0;i<10;i++)
printf("%d ",sort[i]);
getchar();
}
例程说明:
(1)首先初始化待排序列sort。
(2)显示最初数组sort中的元素排列情况。
(3)对数列sort进行快速排序,这里sort为数组sort的首地址;10为数组sort的元素个数;sizeof(int) 为待排序列中每个元素的字节数,大小为2个字节;CMP为用户定义的比较函数的指针。
(4)最后显示出排序后(从小到大排序)数组sort中的元素排列情况。
本例程的运行结果为:
The array that is before sort
3 2 6 12 1 7 -5 9 30 16
The array that is after sort
-5 1 2 3 6 7 9 12 16 30
注意:
1、关于用户提供的比较函数:
qsort函数需要用户提供一个比较搜索函数。该函数由qsort函数调用,并向该比较搜索函数传递两个指针参数a和b。用户定义的比较函数必须在a<b时返回-1,在a=b时返回0,在a>b时返回1。这里的大于、小于、等于,完全由用户来定义。本例程中定义的大于、小于、等于就是数学上的大于、小于、等于。
2、快速排序简介:
快速排序是一种经典的高效排序算法。它是取待排序列中某个元素为基准,按照该元素值的大小将整个序列划分为左右两个子序列,其中左子序列的值小于或等于基准元素的值;右子序列的值大于或等于基准元素的值。然后分别对两个子序列重复上述排序过程,直至所有元素都排在相应位置为止。
有关快速排序算法的详细介绍,请参看数据结构、算法分析等书目。