快速排序qsort()源码及使用实例。

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 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值