#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmp(void* e1, void* e2) //比较两个元素的大小函数
{
if(*(char*)e1 - *(char*)e2 > 0) //这个cmp函数要自己写,只要把(char*)换成你传入的要比较
//的数据类型就可以了
return 1;
else if(*(char*)e1 - *(char*)e2 < 0)
return -1;
else
return 0;
}
void exchange(char* element1, char* element2, int width)
{
int i = 0;
for(i = 0; i < width; i++) //交换元素位置
{
char tmp = *element1;
*element1 = *element2;
*element2 = tmp;
element1++;
element2++;
}
}
void bubble_sort(void* base, int sz, int width, int (*cmp)(void* e1, void* e2))
{
int i = 0;
for(i = 0; i < sz; i++)
{
int j = 0;
for(j = 0; j < sz - i -1; j++)
{
if(cmp(base+j*width, base+(j+1)*width) > 0)//数组首地址+元素宽度*起始位置
{
exchange(base + j*width, base+(j+1)*width, width);
}
}
}
}
int main()
{
//int arr[10] = {3,2,1,4,5,10,7,8,9,6};
char arr[10] = {'e','f','c','g','a','b','u','y','z','h'};
int sz = sizeof(arr)/sizeof(arr[0]);
int width = sizeof(arr[0]);
bubble_sort(arr, sz, width, cmp);//1,需要比较的数组 2,元素个数,3,元素占字节数,4,比较函数
return 0;
}
通用型冒泡排序
最新推荐文章于 2023-11-23 02:00:40 发布