文章目录
1.qsort函数的介绍
2.qsort实现不同类型数据排序
3.qsort的模拟实现
1.qsort函数的介绍
void* base
size_t num
size_t width
int (compar)(const void,const void*)
2.qsort实现不同类型数据排序
define _CRT_SECURE_NO_WARNINGS
include<stdio.h>
include<stdlib.h>
include<string.h>
int cmp_int(const void e1, const void e2)
{
return (*(int*)e1 - *(int*)e2);
}
void test1()
{
int arr[] = {9,8,7,6,5,4,3,2,1,0};
int sz = sizeof(arr) / sizeof(arr[0]);
qsort(arr, sz, sizeof(arr[0]), cmp_int);
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
}
struct Stu
{
char name[20];
int age;
};
int cmp_stu_by_name(const void e1, const e2)
{
return strcmp(((struct Stu*)e1)->name, ((struct Stu*)e2)->name);
}
void test2()
{
struct Stu s[] = { {"zhangsan",20},{"lisi",21},"wangwu",19};
int sz = sizeof(s) / sizeof(s[0]);
qsort(s, sz, sizeof(s[0]), cmp_stu_by_name);
int i = 0;
for (i = 0; i < 3; i++)
{
printf("%s %d ", s[i].name, s[i].age);
}
}
int main()
{
test1();
prinf("\n");
test2();
return 0;
}
int main()
{
int a = 10;
char* pa = &a;
return 0;
}
3.qsort的模拟实现
//交换
void Swap(char buf1, char buf2, int width)
{
int i = 0;
for (i = 0; i < width; i++)
{
char tmp = *buf1;
*buf1 = *buf2;
*buf2 = tmp;
buf1++;
buf2++;
}
}
void bubble_sort(void base, int sz, int width, int(cmp)(const void e1, const void e2))
{
int i = 0;
for (i = 0; i < sz - 1; i++)
{
//一趟排序
int flag = 1;
int j = 0;
for (j = 0; j < sz - 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);
flag = 0;
}
}
if (flag == 1)
break;
}
}
int cmp_int(const void e1, const void e2)
{
return (*(int*)e1 - *(int*)e2);
}
void test1()
{
int arr[] = { 9,8,7,6,5,4,3,2,1,0 };
int sz = sizeof(arr) / sizeof(arr[0]);
qsort(arr, sz, sizeof(arr[0]), cmp_int);
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
}
struct Stu
{
char name[20];
int age;
};
int cmp_stu_by_name(const void e1, const e2)
{
return strcmp(((struct Stu*)e1)->name, ((struct Stu*)e2)->name);
}
void test2()
{
struct Stu s[] = { {"zhangsan",20},{"lisi",21},"wangwu",19};
int sz = sizeof(s) / sizeof(s[0]);
bubble_sort(s, sz, sizeof(s[0]), cmp_stu_by_name);
int i = 0;
for (i = 0; i < 3; i++)
{
printf("%s %d ", s[i].name, s[i].age);
}
}
int main()
{
test1();
printf("\n");
test2();
return 0;
}