qsort是函数库自带的快速排序函数,c中qsort函数包含在stdlib.h的头文件.
其函数原型为:void __fileDECL qsort ( void base, size_t num, size_t width, int (__fileDECL *comp)(const void , const void * )
各个参数分别是:
1、base —— 待排序数组首地址
2、num —— 数组中待排序元素数量
3、width—— 各元素的占用空间大小
4、comp—— 指向函数的指针,用于确定排序的顺序
事实上,qsort是快速排序,但是其排序方式需要自己编写。下面介绍几种排序方式(本文均采用从小到大排序)
一、对int类型数组排序
int num[100];
int cmp(const void *a,const void *b)
{
return *(int *)a - *(int *)b;
}
qsort(num,sizeof(num)/sizeof(num[0]),sizeof(num[0]),cmp);
二、对char类型数组排序
char word[100];
int cmp( const void *a , const void *b )
{
return *(char *)a - *(int *)b;
}
qsort(word,sizeof(word)/sizeof(word[0]),sizeof(word[0]),cmp);
三、对结构体排序
struct In
{
double data;
int other;
}s[100]
//按照data的值从小到大将结构体排序,关于结构体内的排序关键数据data的类型可以很多种,参考上面的例子写
int cmp( const void *a ,const void *B)
{
return (*(In *)a)->data > (*(In *)B)->data ? 1 : -1;
}
qsort(s,100,sizeof(s[0]),cmp);
下面给出qsort的模拟实现:
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a,const void *b)
{
return *(int *)a - *(int *)b;
}
void Swap(char* buf1, char* buf2, int width)
{
int i = 0;
for (i=0; i<width; i++)
{
char tmp = *buf1;
*buf1 = *buf2;
*buf2 = tmp;
buf1++;
buf2++;
}
}
void bubble_sort(void *base, int sz, int width, int (*cmp)(const void*,const void*))
{
int i = 0;
for(i=0; i<sz-1; i++)
{
int j = 0;
for (j=0; j<sz-i-1; j++)
{
if(cmp((char*)base+j*width, (char*)base+(j+1)*width)>0)
{
Swap((char*)base+j*width, (char*)base+(j+1)*width, width);
}
}
}
}
int main()
{
int arr[] = {5,7,8,3,4,1,9};
int i = 0;
bubble_sort(arr, sizeof(arr)/sizeof(arr[0]), sizeof(arr[0]), cmp);
for(i=0; i<sizeof(arr)/sizeof(arr[0]); i++)
{
printf("%d ",arr[i]);
}
system("pause");
return 0;
}
上述模拟实现是以对int类型数组排序为例。
本文详细介绍了C语言中qsort函数的使用方法及其参数解释,并提供了针对不同数据类型的排序示例,包括int类型数组、char类型数组及结构体数组的排序实现。
8025

被折叠的 条评论
为什么被折叠?



