#include<stdio.h>
#include<stdlib.h>
typedef struct Books {
char name[5];
int num;
}books;
books b1[10];
int cmp_int(const void* a1, const void* a2)
{
return *(int*)a1 - *(int*)a2;
}
int cmp_str(const void* a, const void* b)
{
return *(char*)a - *(char*)b;
}
int cmp_dou(const void* a1, const void* a2)
{
return *(double*)a1 > *(double*)a2 ? 1 : -1;
}
int cmp_books(const void* a, const void* b)
{
books* pa1 = (books*)a;
books* pa2 = (books*)b;
if (pa1->name != pa2->name)
{
return (pa1->name) > (pa2->name) ? 1 : -1;
}
else
return (pa1->num) > (pa2->num) ? 1 : -1;
}
int main()
{
int arr[5] = { 5,8,9,7,6 };
char str[] = {'a', 'h', 'e', 'b','x'};
double arr2[] = { 1.1,5.6,2.3,8.8,6.6 };
qsort(arr, sizeof(arr) / sizeof(arr[0]), sizeof(arr[0]), cmp_int);//int型排序
qsort(str, sizeof(str)/sizeof(str[0]), sizeof(str[0]), cmp_str);//char型排序
qsort(arr2, sizeof(arr2) / sizeof(arr2[0]), sizeof(arr2[0]), cmp_dou);//double型排序
int i = 0;
printf("int型排序:\n");
for (i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
{
printf("%d ", arr[i]);
}
printf("\n");
printf("char型排序:\n");
for (i = 0; i < sizeof(str) / sizeof(str[0]); i++)
{
printf("%c ", str[i]);
}
printf("\n");
printf("double型排序:\n");
for (i = 0; i < sizeof(arr2) / sizeof(arr2[0]); i++)
{
printf("%.1f ", arr2[i]);
}
char arr3[] = {3,4,2,7,1,8,9,12,11,56};
for (i = 0; i < 10; i++)
{
b1[i].num = arr3[i];
}
qsort(b1, 10, sizeof(books), cmp_books);
printf("\n");
printf("结构体排序:\n");
for (i = 0; i < 10; i++)
{
printf("%d ", b1[i].num);
}
return 0;
}
//模拟sqort实现通用的冒泡排序
#include<stdio.h>
int int_cmp(const void* a, const void* b)
{
return (*(int*)a > *(int*)b);
}
void swap(void* a1, void* a2,int size)
{
int i = 0;
for (i = 0; i < size; i++)
{
char tmp = *((char*)a1 + i);
*((char*)a1 + i) = *((char*)a2 + i);
*((char*)a2 + i) = tmp;
}
}
void bubble(void* base, int count, int size, int(*cmp)(void*, void*))
{
int i = 0;
int j = 0;
for (i = 0; i < count - 1; i++)
{
for (j = 0; j < count - i - 1; j++)
{
if ((int_cmp((char*)base + j * size, (char*)base + (j + 1) * size))>0)
{
swap((char*)base + j * size, (char*)base + (j + 1) * size,size);
}
}
}
}
int main()
{
int arr[] = { 1,4,6,8,3,5,7,9 };
bubble(arr,sizeof(arr)/sizeof(arr[0]),sizeof(arr[0]),int_cmp);
int i = 0;
for (i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
{
printf("%d ", arr[i]);
}
return 0;
}