int cmp_string(const void *s, const void *t)
{
return strcmp(*(char **)s, *(char **)t);
}
int cmp_int(const void *x, const void *y)
{
int *_x = (int*)x;
int *_y = (int*)y;
if (*_x > *_y) {
return 1;
}
else if (*_x < *_y) {
return -1;
}
else {
return 0;
}
}
int cmp_float(const void*m, const void *n)
{
float*_m = (float*)m;
float*_n = (float*)n;
if (*_m > *_n) {
return -1;
}
else if (*_m < *_n) {
return 1;
}
else {
return 0;
}
}
int main()
{
char *str[] = {"aaaa","eeee","cccc","dddd","bbbb"};
int len = sizeof(str) / sizeof(str[0]);
qsort(str, len, sizeof(char*), cmp_string);
int arr[] = { 1, 3, 5, 8, 9, 6, 0 };
int size = sizeof(arr) / sizeof(arr[0]);
qsort(arr, size, sizeof(int), cmp_int);
float a[] = { 1.0,2.0,7.0,3.0,4.0,0.0 };
int sz = sizeof(arr) / sizeof(arr[0]);
qsort(a, sz, sizeof(float), cmp_float);
system("pause");
return 0;
}
模拟实现qsort :
void qsort (void *start,size,sizeof(int),int (*cmp)(const void*,const void*))
//(数组首地址,数组大小,每个元素大小,cmp函数);
//字符串在传数据大小时需要用 sizeof(char*)
int cmp(const void *x, const void *y)
{
return (*(int *)x) - (*(int *)y);
}
//int cmp_int(const void *x, const void *y)
//{
// int *_x = (int*)x;
// int *_y = (int*)y;
// if (*_x > *_y) {
// return 1;
// }
// else if (*_x < *_y) {
// return -1;
// }
// else {
// return 0;
// }
//
//} cmp 另一种实现方法
void Swap(char *x, char *y, int width)
{
while (width--)
{
*x ^= *y;
*y ^= *x;
*x ^= *y;
x++, y++;
}
}
void my_qsort(void *arr, int sz, int width,int(*cmp)(void*,void*))
{
assert(arr&&cmp);//检查不为空
int i = 0;
int j = 0;
for (i = 0; i < sz-1; i++)
{
int flag = 0;
for (j = 0; j < sz - i - 1; j++)
{
if (cmp((char *)arr + j*width, (char *)arr + (j + 1)*width)>0)//比较
{
flag = 1;
Swap((char *)arr + j*width, (char *)arr + (j + 1)*width, width);//交换
}
}
if (flag == 0) {
break;
}
}
}
int main()
{
int arr[] = { 1,24,5,6,7,8, };
int sz = sizeof(arr) / sizeof(arr[0]);
int i = 0;
my_qsort(arr, sz, sizeof(int), cmp);
for (; i < sz; i++) {
printf("%d ", arr[i]);
}
printf("\n");
system("pause");
return 0;
}