Qsort()函数





函数简介

功 能: 使用快速排序例程进行排序

头文件:stdlib.h

用 法: void qsort(void *base,int nelem,int width,int (*fcmp)(const void *,const void *));

参数: 1 待排序数组首地址

2 数组中待排序元素数量

3 各元素的占用空间大小

4 指向函数的指针,用于确定排序的顺序

用法

使用qsort()排序并用 bsearch()搜索是一个比较常用的组合,使用方便快捷。

qsort 的函数原型是

voidqsort(
void*base,
size_tnum,
size_twidth,
int(__cdecl*compare)(constvoid*,constvoid*)
);

其中base是排序的一个集合数组,num是这个数组元素的个数,width是一个元素的大小,comp是一个比较函数。

比如:对一个长为1000的数组进行排序时,int a[1000]; 那么base应为a,num应为 1000,width应为 sizeof(int),comp函数随自己的命名。

qsort(a,1000,sizeof(int),comp);

其中comp函数应写为:

intcomp(constvoid*a,constvoid*b)
{
return*(int*)a-*(int*)b;
}

上面是由小到大排序,return *(int *)b - *(int *)a; 为由大到小排序。

MSDN:

The qsort function implements a quick-sort algorithm to sort an array of num elements, each of width bytes. The argument base is a pointer to the base of the array to be sorted. qsort overwrites this array with the sorted elements. The argument compare is a pointer to a user-supplied routine that compares two array elements and returns a value specifying their relationship. qsort calls the compare routine one or more times during the sort, passing pointers to two array elements on each call:

以下为compare函数原型 //comp

compare( (void *) & elem1, (void *) & elem2 );

Compare 函数的返回值

描述

< 0

elem1将被排在elem2前面

0

elem1 等于 elem2

> 0

elem1 将被排在elem2后面

对一维数组的排序实例(从小到大排序):

#include<stdio.h>
#include<stdlib.h>
intcomp(constvoid*a,constvoid*b)
{
return*(int*)a-*(int*)b;
}
intmain()
{
int*array;
intn;
scanf("%d",&n);
array=(int*)malloc(n*sizeof(int));
inti=0;
for(;i<n;i++)
{
scanf("%d",(array+i));
}
qsort(array,n,sizeof(int),comp);
for(i=0;i<n;i++)
{
printf("%d\t",array[i]);
}
return0;
}

对一个二维数组进行排序:

int a[1000][2]; 其中按照a[0]的大小进行一个整体的排序,其中a[1]必须和a[0]一起移动交换。//即第一行和第二行(a[0]和a[1]分别代表第一行和第二行的首地址)。使用库函数排序的代码量并不比用冒泡排序法小,但速度却快很多。

qsort(a,1000,sizeof(int)*2,comp);

intcomp(constvoid*a,constvoid*b)

{
return((int*)a)[0]-((int*)b)[0];
}

你可能感兴趣的:(编程,C++,快速排序)