1,普通冒泡排序:
void bubble(int arr[], int sz)
{
int i = 0;
for (i = 0; i < sz-1; i++)
{
int j = 0;
for (j = 0; j < sz - 1 - i; j++)
{
if (arr[j] > arr[j+1])
{
int temp = 0;
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main()
{
int arr[10] = { 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 };
int sz = sizeof(arr) / sizeof(arr[0]);
bubble(arr, sz);
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
int cmp_int(const void*e1, const void*e2)
{
return *(int*)e1 - *(int*)e2;
}
int main()
{
int arr[10] = { 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 };
int sz = sizeof(arr) / sizeof(arr[0]);
qsort(arr, sz,sizeof(arr[0]),cmp_int);
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
3,对字符串排序:
struct S
{
char name[20];
int age;
char sex[5]; //定义结构体类型
};
int cmp_name(const void*e1, const void*e2)
{
return strcmp((*(struct S*)e1).name, (*(struct S*)e2).name);
}
int main()
{
struct S arr[3] = { { "zhangsan", 25, "nan" }, { "lisi", 20, "nv" }, { "xiaoli", 10, "nv" } };
int sz = sizeof(arr) / sizeof(arr[0]);
bubble_sort(arr, sz, sizeof(arr[0]), cmp_name); //仅对name进行了排序
return 0;
}
struct S
{
char name[20];
int age;
char sex[5];
};
int cmp_age(const void*e1, const void*e2)
{
return (*(struct S*)e1).age - (*(struct S*)e2).age;
}
int cmp_name(const void*e1, const void*e2)
{
return strcmp((*(struct S*)e1).name, (*(struct S*)e2).name);
}
void _swap(char* buf1, char*buf2, int width)
{
int i = 0;
assert(buf1);
assert(buf2);
for (i = 0; i < width; i++)
{
int temp = *buf2;
*buf1 = *buf2;
*buf2 = temp;
buf1++;
buf2++;
}
}
void bubble_sort(void* base,int sz,int width,int (*cmp)(const void*,const void*))
{
int i = 0;
for (i = 0; i < sz - 1; i++)
{
int j = 0;
for (j = 0; j <= sz - i - 1; j++)
{
if (cmp((char*)base + j*width,(char*)base + (j + 1)*width )>0)
_swap((char*)base + j*width, (char*)base + (j + 1)*width,width);
}
}
}
int main()
{
struct S arr[3] = { { "zhangsan", 25, "nan" }, { "lisi", 20, "nv" }, { "xiaoli", 10, "nv" } };
int sz = sizeof(arr) / sizeof(arr[0]);
bubble_sort(arr, sz, sizeof(arr[0]), cmp_age);
return 0;
}