C语言模拟实现标准库函数之qsort()

qsort

编译器函数库自带的快速排序函数。

void qsort(void*base,size_t num,size_t width,int(__cdecl*compare)(const void*,const void*));

参数解释:
  • void*base-待排序数组首地址
  • size_t num-数组中待排序元素数量
  • size_t width-各元素的占用空间大小
  • int(__cdecl*compare)(const void*,const void*)-指向比较两个元素的函数的指针
qsort函数的用法
#include <stdio.h>      /* printf */
#include <stdlib.h>     /* qsort */

int compare (const void * a, const void * b)
{
  return ( *(int*)a - *(int*)b );
}

int main ()
{
  int n;
  int values[] = { 40, 10, 100, 90, 20, 25 };
  qsort (values, 6, sizeof(int), compare);
  for (n=0; n<6; n++)
     printf ("%d ",values[n]);
  system("pause");
  return 0;
}

这里写图片描述

例子2:

#include <stdio.h>      /* printf */
#include <stdlib.h>     /* qsort */

int compare(const void * a, const void * b)
{
    return (*(int*)a - *(int*)b);
}

int main()
{
    char s[3][4] = { "z","g","c" };  //字符串数组排序 
    qsort(s, 3, sizeof(s[0]), compare); //sizeof(s[0])=sizeof(char)
    for (int i = 0; i<3; i++)
        printf("%s\n", s[i]);
    system("pause");
    return 0;
}

这里写图片描述

模拟实现qsort

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>

/*
判断n1,n2元素大小,n1比n2大返回正数;小返回负数,相同返回0
*/
int cmp(const void*n1, const void*n2)
{
    return *(char*)n1 - *(char*)n2;                //升序  
}

/*
交换每个字节
sizeof(char) = 1;sizeof(int ) = 4;
sizeof(arr1[0])=1;sizeof(arr[0])=4;
*/
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* n1, const void*n2))      //模拟实现qsort  
{
    int i = 0;
    for (i = 0; i < sz - 1; i++)
    {
        int j = 0;
        for (j = 0; j < sz - 1 - i; j++)
        {
            int ret = cmp(((char*)base + (j*width)), ((char*)base + (j + 1)*width));
            if (ret>0)
            {
                Swap(((char*)base + (j*width)), ((char*)base + (j + 1)*width), width);
            }
        }
    }
}

int main()
{
    int i = 0;
    int arr[] = { 1, 4, 7, 5, 6, 9 };
    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]);
    }
    printf("\n");


    /*
    printf输出格式"%s"
    */
    char arr1[] = { 'a','f','y','w','b' };
    bubble_sort(arr1, sizeof(arr1) / sizeof(arr1[0]), sizeof(arr1[0]), cmp);
    for (i = 0; i < sizeof(arr1) / sizeof(arr1[0]); i++)
    {
        printf("%c ", arr1[i]);
    }
    printf("\n");
    system("pause");
    return 0;
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值