題目:回調(diào)函數(shù)實現(xiàn)冒泡排序 排整數(shù)也可排字符串 n為數(shù)組元素大小
#define _CRT_SECURE_NO_WARNINGS 1#include <stdio.h>#include <stdlib.h>#include <string.h>//交換函數(shù) 交換n1 n2指向的變量 按字節(jié)交換 交換size個字節(jié)的大小void swap(char *n1, char *n2,int size){int i = 0;while(i < size){char temp = *(n1 + i);*(n1 + i) = *(n2 + i);*(n2 + i) = temp;i++;}}//整數(shù)比較函數(shù)int int_cmp(const void *elem1,const void *elem2){return (*(int *)elem1 - *(int *)elem2);}//字符串比較函數(shù)int str_cmp(const void *s1, const void *s2){ //return strcmp((char *)*(int *)s1, (char *)*(int *)s2);return strcmp((char *)*(int *)s1, (char *)*(int *)s2);//由字符串指針數(shù)組的數(shù)組元素的地址s1找到s1元素中存放的地址內(nèi)容}//回調(diào)函數(shù)實現(xiàn)冒泡排序 排整數(shù)也可排字符串 n為數(shù)組元素大小void bubble(void *base, int n, int size,int(*cmp)(const void *elem1, const void *elem2 )){int i = 0;int j = 0;for (i = 0;i < n - 1;i++){for (j = 0;j < n - 1 - i; j++){if (cmp((char *)base + j*size, (char *)base + (j + 1)*size) > 0){swap((char *)base + j*size, (char *)base + (j + 1)*size, size);}}}} int main() { int arr_int[]={10,9,8,7,6,5,4,3,2,1}; int i = 0; char *S[] = {"rrrrrrrrrrrrr","aaaaaaaaaaa","bbbbbbbbbbb","hhhhhhhhh","eeeeeeeeeeee"}; bubble(arr_int,10,sizeof(int),int_cmp); for(i = 0;i < sizeof(arr_int)/sizeof(arr_int[0]);i++) {printf("%d ",arr_int[i]); } printf("\n"); bubble(S,sizeof(S)/sizeof(S[0]),sizeof(char *),str_cmp); for(i = 0;i < sizeof(S)/sizeof(S[0]);i++) printf("%s\n",S[i]); printf("\n");system("pause");return 0; }