用回调函数与指针参考c语言库函数q_sort函实现bublling_sort 函数排序各种类型的数组

#define  _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
int compare_plus_int(const void* e1, const void* e2) {
    return *((int*)e1) - *((int*)e2);

}//实现int 类型的数组比较大小
int compare_plus_char(const void* e1, const void* e2) {

    return *((char*)e1) - *((char*)e2);
}
//实现char类型的数组比较大小
void swap(const void* e1, const void* e2, int width) {
    int i = 0;
    int tmp = 0;
    for (i = 0; i < width; i++)
    {//交换两个元素的字节
        tmp = *((char*)e1 + i);//将空类型的指针强制类型转换为(char*)类型,由于char*的步长为1,更加容易理解
        *((char*)e1 + i) = *((char*)e2 + i);
        *((char*)e2 + i) = tmp;
    }
}//采用const void* 类型的指针,已实现通用的交换函数
void bubbling_sorts(void* base, int sz, int width, int(*cmp)(const void* e1, const void* e2))
{   //实现一下这个高贵的函数
    int i = 0;
    int j = 0;
    for (i = 0; i < sz - 1; i++) {
        for (j = 0; j < sz - 1 - i; 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 numbers[] = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5 };
int size = sizeof(numbers) / sizeof(numbers[0]);

bubbling_sorts(numbers, size, sizeof(int), compare_plus_int);
for (int i = 0; i < size; i++) {
    printf(&quot;%d &quot;, numbers[i]);
}

return 0;
}
//打印排序后的数组!
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务