qsort()是最有效的快排序法之一。其函数原型是
viod qsort(void *base, size_t_nmemb, size_t_size, int (*compar)( const void *), const void *);
第一个参数为指向要排序的数组头部的指针。
第二个参数为需要排序的项目数量。因为qsort()将第一个参数转换为void指针,所以会失去每个数组元素大小的信息,为了补充该信息,需要将数组大小告诉qsort()。
第三个参数是一个指向函数的指针,被指向的函数用于确定排序顺序。这个比较函数应该接受两个参数,即分别指向进行比较的两个项目的指针。
以下是调用qsort()函数的函数实例。
/*
qsorter.c 使用qsort()对一组数字排序
*/
#include <stdio.h>
#include <stdlib.h>
#define NUM 40
void fillarray (double ar[], int n);
void showarray (const double ar[], int n);
int mycopy(const void *p1, const void *p2);
int main (void)
{
double vals[NUM];
fillarray(vals,NUM);
puts("Random list:");
showarray(vals, NUM);
qsort(vals,NUM,sizeof (double),mycopy);
puts("\nSorted list:");
showarray(vals,NUM);
return 0;
}
void fillarray (double ar[], int n)
{
int index;
for (index = 0; index < n; index ++)
{
ar[index] = (double)rand()/((double)rand()+0.1);
}
}
void showarray (const double ar[], int n)
{
int index;
for (index = 0; index < n; index ++)
{
printf ("%9.4f",ar[index])
if (index & 6 == 5)
putchar('\n');
}
if (index % 6 != 0)
putchar('\n');
}
int mycopy (const void *p1, const void *p2)
{
const double *a1 = (const double *) p1;
const double *a2 = (const double *) p2;
if (*a1 < *a2)
return -1;
else if (*a1 == *a2)
return 0;
else
return 1;
}
----------------------------------------------------------------以下是搜索到的qsort()函数源码---------------------------------------------------------
<pre id="best-content-281179165" class="best-text mb-10">void __fileDECL qsort (
void *base,
size_t num,
size_t width,
int (__fileDECL *comp)(const void *, const void *)
)
#endif /* __USE_CONTEXT */
{
char
快速排序qsort()源码及使用实例。
最新推荐文章于 2024-03-26 07:00:00 发布