#include<stdio.h>
int cmp(const void* x1, const void* x2)
{
return (*(int*)x1 - *(int*)x2);
}
void Swap(char* x, char* y, int width) //将两个数改为char*类型,每次只交换一个字节,直到将int*的四个字节全部交换一遍
{
int i = 0;
for (i = 0; i < width; i++)
{
char tmp = *x;
*x = *y;
*y = tmp;
x++;
y++;
}
}
sqort_moni(int* arr,int sz,int width, int (*cmp)(const void*, const void*))
{
int i,j;
for (i = 0; i < sz - 1; i++)
{
int flag = 1;
for (j = 0; j < sz - 1 - i; j++)
{
if (cmp((char*)arr + j * width, (char*)arr + (j + 1) * width )> 0) //返回值大于0,则说明x1>x2,需要顺序排列则要交换两个数
{
Swap((char*)arr + j * width, (char*)arr + (j + 1) * width, width);
flag = 0;
}
}
if (flag == 1) //如果循环一整遍之后都符合条件,则直接跳出循环
{
break;
}
}
}
int main()
{
int arr[10] = {9,8,7,6,5,4,3,2,1,0};
int sz = sizeof(arr) / sizeof(arr[0]);
sqort_moni(arr,sz,sizeof(arr[0]), cmp);
for (int i = 0; i < sz; i++)
{
printf("%d ",arr[i]);
}
return 0;
}