qsort函数的冒泡排序实现
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
//int 类型的比较函数
int cmp_int(const void *a, const void *b)
{
return *(int*)a - *(int*)b;
}
//字符数组的比较函数
int cmp_str(const void *str1, const void *str2)
{
return strcmp(*(char**)str1, *(char**)str2);
}
//两个变量交换,width为交换宽度
void Sort(char *str1, char *str2, size_t width)
{
unsigned int i = 0;
for (i = 0; i < width; i++)
{
char tmp = *str1;
*str1 = *str2;
*str2 = tmp;
str1++;
str2++;
}
}
//qsort函数的冒泡排序实现
void Bubble(void *base, size_t num, size_t width, int(*cmp)(const void *el1, const void *el2))
{
assert(base && cmp);
int i = 0;
int j = 0;
int flag = 0;
for (i = 0; i < num - 1; i++)
{
flag = 0;
for (j = 0; j < num - i - 1; j++)
{
if (cmp((char*)base + j * width, (char*)base + (j + 1) * width) > 0)
{
Sort((char*)base + j * width, (char*)base + (j + 1) * width, width);
flag = 1;
}
}
//冒泡排序的优化
if (0 == flag)
{
break;
}
}
}
int main()
{
/*
测试部分
int arr[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
int i = 0;
int sz = sizeof(arr) / sizeof(arr[0]);
qsort(arr, sz, sizeof(arr[0]), cmp_int);
Bubble(arr, sz, sizeof(arr[0]), cmp_int);
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}*/
char str[][4] = { "ddd", "ccc", "bbb", "aaa" };
int sz = sizeof(str) / sizeof(str[0]);
//qsort(str, sz, sizeof(str[0]), cmp_str);
Bubble(str, sz, sizeof(str[0]), cmp_str);
printf("%s\n", str[0]);
printf("%s\n", str[1]);
printf("%s\n", str[2]);
printf("%s\n", str[3]);
return 0;
}
1.冒泡排序的优化:如果进行到if语句时,flag为0,则上一轮遍历中没有进行元素的交换,说明已经排序完成不需要再进行排序了。
2.其中int(*cmp)(const void *el1, const void *el2) , 表示一个函数指针。指针cmp指向一个函数,这个函数的参数类型为const void*和const void*,返回类型为int。参数指针类型为void,表示其可以接受任意类型的指针,但在使用时必须进行强制类型转换。
3.C语言库函数中,qsort函数作用是进行快速排序。qsort函数的声明:
void qsort( void *base, size_t num, size_t width, int ( *cmp )(const void *em1, const void *em2 ) );
(1)base为要排序的数组的首元素地址,类型为void*;
(2)size_t 表示无符号整型;
(3)num 为要排序的元素个数;
(4)width 为要排序的每个元素的大小,单位为字节;qsort函数通过宽度实现交换不同类型的值;
(5)cmp为一个函数指针,该指针指向的函数描述了每个元素大小比较的方式。该函数需要使用者自己编写,有了比较方式才可以进行排序。因为这个函数指针使qsort函数可以对任意类型进行排序。