#include <stdio.h>
void swap(void* a, void* b, size_t width)
{
for (int i = 0; i < width; i++) //a,b两数组间的值进行交换
{
int tmp = *((char*)a + i);
*((char*)a + i) = *((char*)b + i);
*((char*)b + i) = tmp;
}
}
int Qsort(void* base, size_t num, size_t width, int (*compare)(const void* elem1, const void* elem2))
{
for (int i = 0; i < num - 1; i++) //采用冒泡排序来模拟快速排序
{
for (int j = 0; j < num - i - 1; j++)
{
if (compare((char*)base + j * width, (char*)base + (j + 1) * width) > 0)
{
swap((char*)base + j * width, (char*)base + (j + 1) * width,width);
}
}
}
}
int comp_int(const void* elem1, const void* elem2)
{
return (*(int*)elem1 - *(int*)elem2); //强制转换为整型
//字符串的比较:strcmp(*char(**)elem1,*(char**)elem2);
}
void main()
{
int ar[] = { 4,8,9,2,3,0,5 };
int n = sizeof(ar) / sizeof(ar[0]);
for (int i = 0; i < n; i++)
{
printf("%d", ar[i]);
}
printf("\n");
qsort(ar, n, sizeof(int), comp_int);
for (int i = 0; i < n; i++)
{
printf("%d", ar[i]);
}
}
运行截图
?
|