思路:仿照qsort函数运用函数指针实现排序×××数组、排序字符串的功能。
首先,编写×××数组比较函数和字符串比较函数;
其次,仿照qsort函数将首元素地址、元素个数、元素大小、比较函数 传参编写熟悉的冒泡排序函数;
最后,举例验证函数正确性。
/******************************///1.编写冒泡排序,可以排序×××数组,也可以排序字符串。#include#include #include void bobble(const void *base, int length, int width, int(*fcmp)(const void *a, const void *b))//(*fcmp)()函数指针{ assert(base);//断言 int i = 0, j = 0, k = 0; char *arr = (char *)base; char temp='\0'; for (i = 0; i < length - 1; i++) for (j = 0; j < length - i - 1; j++) { if ((*fcmp)(arr, arr + width * j)>0)//传参 将该元素地址与下一元素地址传入函数 { for (k = 0; k < width * j; k++)//运用循环在内存中实现对两元素进行交换 { temp = *(arr + k); *(arr + k) = *(arr + k + width * j); *(arr + k + width * j) = temp; } } }}int int_cmp1(const void *a, const void *b){ assert(a); assert(b); return *(int *)a - *(int *)b;}int str_cmp(const void *a, const void *b){ assert(a); assert(b); char *arr1 = (char *)a; char *arr2 = (char *)b; while (*arr1&&*arr2&&*arr1++ == *arr2++) ; return *(arr1 - 1) - *(arr2 - 1);}int main(){ int str1[] = { 1,5,0,2,4,7,9,6,3,5,6 ,16,155,26}; int size = sizeof(str1) / sizeof(str1[0]); char str2[][30] = { "abcd","3456","cdef","1234" ,"abce"}; int size_str = sizeof(str2) / sizeof(str2[0]); int i = 0; qsort(str1, size, sizeof(str1[0]), int_cmp1);//用快排函数结果作比较 for (i = 0; i < size; i++) printf("%d ", str1[i]); printf("\n"); bobble(str1, size, sizeof(str1[0]), int_cmp1); for (i = 0; i < size; i++) printf("%d ", str1[i]); printf("\n"); qsort(str2, size_str, sizeof(str2[0]), str_cmp);//用快排函数结果作比较 for (i = 0; i < size_str; i++) printf("%s\n", str2[i]); bobble(str2, size_str, sizeof(str2[0]), str_cmp); for (i = 0; i < size_str; i++) printf("%s\n", str2[i]); system("pause"); return 0;}