回复 2楼 rjsp
struct stu
{
char name[30];
int rank;
};
int comp_int(const void* e1, const void* e2)
{
return *(int*)e1 - *(int*)e2;
}
int comp_float(const void*e1, const void*e2)
{
if (*(float*)e1 == *(float*)e2)
return 0;
else if (*(float*)e1 > *(float*)e2)
return 1;
else
return -1;
}
int comp_struct_by_rank(const void*e1, const void*e2)
{
return ((struct stu*)e1)->rank - ((struct stu*)e2)->rank;
}
int comp_struct_by_name(const void*e1, const void*e2)
{
return strcmp(((struct stu*)e1)->name, ((struct stu*)e2)->name);
}
void exchange(char*e1, char* e2,int width)
{
char tem;
for (int i = 0; i < width; i++)
{
tem = *e1;
*e1 = *e2;
*e2 = tem;
e1++;
e2++;
}
}
void bubble(void* arr, int num, int width,int(*comp)(const void*e1,const void*e2))
{
int i = 0;
int j = 0;
for(i = 0; i < num - 1; i++)
{
for (j = 0; j < num - 1 - i; j++)
{
if (comp(
(char*)arr + (width * j), (char*)arr + (width * (j + 1))
) > 0)
{
exchange((char*)arr + width * j, (char*)arr + width * (j + 1), width);
}
}
}
}
void text1_int()
{
int arr[10] = { 2,6,4,8,7,9,5,1,3,0 };
int num = sizeof(arr) / sizeof(arr[0]);
qsort(arr, num, sizeof(arr[0]), comp_int);
for (int i = 0; i < 10; i++)
{
printf("%d ", arr[i]);
}
}
void text2_float()
{
float arr1[10] = { 2.6f,6.3f,4.5f,8.4f,7.9f,9.5f,5.3f,1.4f,3.7f,0.8f };
int num = sizeof(arr1) / sizeof(arr1[0]);
qsort(arr1, num,sizeof(arr1[0]), comp_float);
for (int i = 0; i < 10; i++)
{
printf("%f ", arr1[i]);
}
}
void text3_struct_rank()
{
struct stu arr3[6] = { {"һ",6} ,{"һһ",4},{"һһһ",3}, {"һһһһ",7},{"һһһһһ",5} ,{"һһһһһһ",8} };
int num = sizeof(arr3) / sizeof(arr3[0]);
qsort(arr3, num, sizeof(arr3[0]), comp_struct_by_rank);
for (int i = 0; i < 6; i++)
{
printf("%d ", arr3[i].rank);
}
}
void text4_struct_name()
{
struct stu arr3[6] = { {"asd",6} ,{"fgh",4},{"jkl",3}, {"zxc",7},{"vbn",5} ,{"qwe",8} };
int num = sizeof(arr3) / sizeof(arr3[0]);
qsort(arr3, num, sizeof(arr3[0]), comp_struct_by_name);
for (int i = 0; i < 6; i++)
{
printf("%s ", arr3[i].name);
}
}
void text5_bubble_int()
{
int arr[10] = { 2,6,4,8,7,9,5,1,3,0 };
int num = sizeof(arr) / sizeof(arr[0]);
bubble(arr, num, sizeof(arr[0]), comp_int);
for (int i = 0; i < 10; i++)
{
printf("%d ", arr[i]);
}
}
int main()
{
text1_int();
printf("\n");
text2_float();
printf("\n");
text3_struct_rank();
printf("\n");
text4_struct_name();
printf("\n");
text5_bubble_int();
/*bubble*/
return 0;
}