#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//void qsort(void*base, size_t num, size_t width, int(__cdecl*compare)(const void*, const void*));
typedef struct student
{
char name[10];
int age;
} student;
void my_Qsort(void*base, size_t num, size_t width, int(__cdecl*compare)(const void*, const void*))
{
void *temp = malloc(width);
for (int i = 0; i < num - 1; i++)
{
for (int j = 0; j < num - 1 - i; j++)
{
if (compare((char*)base + j*width, (char*)base + (j + 1)*width)>0)
{
memcpy(temp, (char*)base + j*width, width);
memcpy((char*)base + j*width, (char*)base + (j + 1)*width, width);
memcpy((char*)base + (j + 1)*width, temp, width);
}
}
}
free(temp);
}
int compare(const void* e1, const void* e2)
{
return strcmp(*(char**)e1, *(char**)e2);
}
int compare_1(const void* e1, const void* e2)
{
return *(int*)e1 - *(int*)e2;
}
int compare_2(const void* e1, const void* e2)
{
return ((student*)e1)->age - ((student*)e2)->age;
}
int main()
{
char* str[] = { "abc", "bcd", "cde", "ade", "abd" };
int a1 = (sizeof(str) / sizeof(str[0]));
for (int i = 0; i < a1; i++)
printf("%s ", str[i]);
printf("\n");
my_Qsort(str, a1, sizeof(char*), compare);
for (int i = 0; i < a1; i++)
printf("%s ", str[i]);
printf("\n");
int arr[] = { 22, 2, 65, 48, 36, 789, 6, 48, 645.12 };
int a2 = (sizeof(arr) / sizeof(arr[0]));
for (int i = 0; i < a2; i++)
printf("%d ", arr[i]);
printf("\n");
my_Qsort(arr, a2, sizeof(int), compare_1);
for (int i = 0; i < a2; i++)
printf("%d ", arr[i]);
printf("\n");
student stu[] = { { "小明", 20 }, { "小红", 21 }, { "小李", 19 } };
int a3 = sizeof(stu) / sizeof(stu[0]);
my_Qsort(stu, a3, sizeof(student), compare_2);
return 0;
}
冒泡实现qsort函数
最新推荐文章于 2024-05-28 14:35:23 发布