通用冒泡排序法qsort的用法与其模拟实现

本文详细介绍了C语言中qsort函数的使用方法及其参数解释,并提供了针对不同数据类型的排序示例,包括int类型数组、char类型数组及结构体数组的排序实现。

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类型数组排序为例。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值