当前位置: 首页> 健康> 养生 > C语言:冒泡排序的注意事项及具体实现

C语言:冒泡排序的注意事项及具体实现

时间:2025/9/8 18:19:00来源:https://blog.csdn.net/2401_85816985/article/details/142277669 浏览次数:0次

一、注意事项

        1、函数声明为:void bubble_sort(void* base, size_t num, size_t width, int (*cmp)(const void* e1, const void* e2));

        2、base 指向所要排序的数组

        3、num 为数组的元素个数

        4、width 为一个元素占多少个字节的空间

        5、cmp 为函数指针,指向用来进行比较的函数

        6、每趟排序都会把当前未排序部分的最大值移到正确的位置

二、具体实现

#include <stdio.h>
#include <assert.h>//交换
void sway(char* buff1, char* buff2, size_t width)
{char tmp = 0;while (width--){tmp = *buff1;*buff1 = *buff2;*buff2 = tmp;buff1++;buff2++;}
}//比较
int cmp_num(const void* e1, const void* e2)
{return *(int*)e1 - *(int*)e2;
}//冒泡排序
void bubble_sort(void* base, size_t num, size_t width, int (*cmp)(const void* e1, const void* e2))
{assert((NULL != base) && (NULL != cmp));//用断言判断 base 以及 cmp 是否为空指针int i = 0;int j = 0;int flag = 1;//假设该数组为有序num--;//趟次 num - 1 次就可以了for (i = 0; i < num; i++)//趟次{flag = 1;for (j = 0; j < num - i; j++)//一趟的过程{if (cmp((char*)base + j * width, (char*)base + (j + 1) * width) > 0){flag = 0;sway((char*)base + j * width, (char*)base + (j + 1) * width, width);}}if (1 == flag)//判断是否有序{return;}}
}int main()
{int arr[] = { 2, 4, 2, 1, 6, 3 };size_t sz = sizeof(arr) / sizeof(arr[0]);bubble_sort(arr, sz, sizeof(arr[0]), cmp_num);//冒泡排序int i = 0;for (i = 0; i < sz; i++){printf("%d ", arr[i]);//结果为:1 2 2 3 4 6}return 0;
}

附:若有不足,望指出。

^_^感谢^_^

关键字:C语言:冒泡排序的注意事项及具体实现

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: