回调函数应用(冒泡排序 既排整型数组 也可排字符串 -电脑资料

电脑资料 时间:2019-01-01 我要投稿
【www.unjs.com - 电脑资料】

    题目:回调函数实现冒泡排序 排整数也可排字符串 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; }

最新文章