传入数组进行排序
//类qsort的多用冒泡排序函数--测试用数组排序
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int compare(const void* e1, const void* e2)
{
return *((int*)e1) - *((int*)e2);
}
void swap(char* e1, char* e2, size_t size)
{
for (int i = 0; i < size; ++i)
{
*(e1 + i) = *(e1 + i) ^ *(e2 + i);
*(e2 + i) = *(e1 + i) ^ *(e2 + i);
*(e1 + i) = *(e1 + i) ^ *(e2 + i);
}
//按照单位倍的次数进行交换两个变量
}
void bubble_sort(void* base, size_t num, size_t size, int (*compare)(const void*, const void*))
{
for (int i = 0; i < num - 1; ++i)
{
for (int j = 0; j < num - 1 - i; ++j)
{
if (compare((char*)base + size * j, (char*)base + size *( j + 1)) > 0)
//将(void*)类型的指针转换为(char*)类型
//再按照单位倍的长度移动指针
swap((char*)base + size * j, (char*)base + size * (j + 1), size);
}
}
}
void print(int* arr, size_t num)
{
for (int i = 0; i < num; ++i)
{
printf("%d ", *(arr + i));
}
printf("\n");
}
void main()
{
int arr[] = { 10,9,8,7,6,5,4,3,2,1 };
size_t num = sizeof(arr) / sizeof(arr[0]);
print(arr, num);
bubble_sort(arr, num, sizeof(arr[0]), compare);
print(arr, num);
}
传入字符串进行排序
//类qsort的多用冒泡排序函数-测试按结构体名称排序
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct stu
{
int age;
char* name;
};
int compare(const void* e1, const void* e2)
{
return strcmp(((struct stu*)e1)->name, ((struct stu*)e2)->name);
}
void swap(char* e1, char* e2, size_t size)
{
for (int i = 0; i < size; ++i)
{
*(e1 + i) = *(e1 + i) ^ *(e2 + i);
*(e2 + i) = *(e1 + i) ^ *(e2 + i);
*(e1 + i) = *(e1 + i) ^ *(e2 + i);
}
}
void bubble_sort(void* base, size_t num, size_t size, int (*compare)(const void*, const void*))
{
for (int i = 0; i < num - 1; ++i)
{
for (int j = 0; j < num - 1 - i; ++j)
{
if (compare((char*)base + size * j, (char*)base + size * (j + 1)) > 0)
swap((char*)base + size * j, (char*)base + size * (j + 1), size);
}
}
}
void print_struct(const struct stu* s, int size)
{
for (int i = 0; i < size; ++i)
printf("%d %s\n", (s + i)->age, (s + i)->name);
}
void main()
{
struct stu s[5] = { {44,"LiHua"}, {21,"XiaoMing"}, {68,"HuangWen"}, {89,"ChangMei"}, {17,"GaoZhi"} };
int size = sizeof(s) / sizeof(s[0]);
printf("名字排序前:>\n");
print_struct(s, size);
bubble_sort(s, size, sizeof(s[0]), compare);
printf("名字排序后:>\n");
print_struct(s, size);
}