qsort排序各种类型的数据
void qsort (void* base, size_t num, size_t size,int (compar)(const void,const void*))
其中base为待排序的数组,num为数组元素个数,size为数组每个元素的大小(以字节为单位),compar为函数指针
**
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//整型
int Integer(const void* p1, const void* p2) {
return *((int*)p1) - *((int*)p2);
}
//字符型
int Character(const void* p1, const void* p2) {
return *((char*)p1) - *((char*)p2);
}
//字符串
int CharacterString(const void* p1, const void* p2) {
return strcmp(*((char**)p1), *((char**)p2));
}
//浮点型
int Float(const void* p1, const void* p2) {
return *((double*)p1) - *((double*)p2);
}
int main() {
int arr1[] = { 0 , 53 , 45 , 89 , 68 , 75 };
qsort(arr1, sizeof(arr1) / sizeof(arr1[0]), sizeof(arr1[0]), Integer);
for (int i = 0; i < sizeof(arr1) / sizeof(arr1[0]); i++) {
printf("%d ", arr1[i]);
}
printf("\n");
char arr2[] = { 'a' , 'f' , 'y' , 'o' ,'r' , 'w' };
qsort(arr2, sizeof(arr2) / sizeof(arr2[0]), sizeof(arr2[0]), Character);
for (int i = 0; i < sizeof(arr2) / sizeof(arr2[0]); i++) {
printf("%c ", arr2[i]);
}
printf("\n");
char* arr3[] = { "can", "I", "sing", "jump", "rap", "and basketball" };
qsort(arr3, sizeof(arr3) / sizeof(arr3[0]), sizeof(arr3[0]), CharacterString);
for (int i = 0; i < sizeof(arr3) / sizeof(arr3[0]); i++) {
printf("%s ", arr3[i]);
}
printf("\n");
double arr4[] = { 0.0 , 82.7 , 16.5 , 16.6 , 50.9 };
qsort(arr4, sizeof(arr4) / sizeof(arr4[0]), sizeof(arr4[0]), Float);
for (int i = 0; i < sizeof(arr4) / sizeof(arr4[0]); i++) {
printf("%f ", arr4[i]);
}
printf("\n");
system("pause");
return 0;
}
**