題目:回調函數實現冒泡排序 排整數也可排字符串 n為數組元素大小
#define _CRT_SECURE_NO_WARNINGS 1#include <stdio.h>#include <stdlib.h>#include <string.h>//交換函數 交換n1 n2指向的變量 按字節交換 交換size個字節的大小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++;}}//整數比較函數int int_cmp(const void *elem1,const void *elem2){return (*(int *)elem1 - *(int *)elem2);}//字符串比較函數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);//由字符串指針數組的數組元素的地址s1找到s1元素中存放的地址內容}//回調函數實現冒泡排序 排整數也可排字符串 n為數組元素大小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; }
这里有更多你想看的
|
- 上一篇:2016紅與黑 紅與黑 百科
- 下一篇:返回列表