#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//用qsort排序各种类型的数据
int comp_t(const void*p1,const void*p2)
{
return (*(int*)p1 - *(int*) p2);
}
//
int main()
{
int i = 0;
int arr[] = { 1,2,3,5,4,9,8,6,0,7};
size_t sz = sizeof(arr) / sizeof(arr[0]);
//排列整形数据
qsort(arr, sizeof(arr)/sizeof(arr[0]),sizeof(int), comp_t);
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
//排序结构体类型数据
struct Stu {
char name[20];
int age;
};
int comp_name(const void* e1,const void* e2)
{
return strcmp(((struct Stu*)e1)->name , ((struct Stu*)e2)->name);
}
int main()
{
struct Stu arr[] = { {"zhuyangyang",18},{"wuwu",19} };
int sz = sizeof(arr) / sizeof(arr[0]);
qsort(arr, sz, sizeof(arr[0]), comp_name);
printf("%s %d", arr->name, arr->age);
return 0;
}
//模拟qsort编写一个函数实现对各种数据的冒泡排序
int comp_t(const void* p1,const void* p2)
{
return *(int*)p1 - *(int*)p2;
}
void _swap(void*p1,void*p2,int size)
{
int i = 0;
for (i = 0; i < size; i++)
{
char tmp = *((char*)p1 + i);
*((char*)p1 + i) = *((char*)p2 + i);
*((char*)p2 + i) = tmp;
}
}
void my_pubble(void* base,int sz,int width,int(*cmp_t)(void*,void*))
{
int i = 0;
for (i = 0; i < sz; i++)
{
int j = 0;
for (j = 0; j < sz - 1 - i; j++)
{
if (comp_t((char*)base + j * width, (char*)base + (j + 1) * width)>0)
{
_swap((char*)base + j * width, (char*)base + (j + 1) * width,width);
}
}
}
}
int main()
{
int arr[] = { 1,4,7,2,5,0,8,9,6,3 };
int i = 0;
my_pubble(arr, sizeof(arr) / sizeof(arr[0]), sizeof(int), comp_t);
for (i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
{
printf("%d ", arr[i]);
}
return 0;
}