#define _CRT_SECURE_NO_WARNINGS 1一、冒泡法排序整数#include<stdio.h>int int_cmp(const void *elem1, const void *elem2){ return (*(int *)elem1 - *(int*)elem2);},void swap(char *n1, char *n2, int sz){ int i = 0; for (i = 0; i < sz; i++) { char tmp = *(n1 + i); *(n1 + i) = *(n2 + i); *(n2 + i) = tmp; }} 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 + size *(j + 1))>0) { swap((char *)base + j*size, (char *)base + size *(j + 1), size); } } } }int main(){ int arr[] = { 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 }; int sz = sizeof(arr) / sizeof(*arr); bubble(arr, sz, sizeof(int), int_cmp); int i = 0; for (i = 0; i < sz; i++) { printf("%d\n", arr[i]); } system("pause"); return 0;} 二、 冒泡法排序字符串#include<stdio.h>int int_cmp(const void *elem1, const void *elem2){ return (*(int *)elem1 - *(int*)elem2);}int str_cmp(const void *p1, const void *p2){ return strcmp((char *)*(int *)p1, (char *)*(int *)p2);}void swap(char *n1, char *n2, int sz){ int i = 0; for (i = 0; i < sz; i++) { char tmp = *(n1 + i); *(n1 + i) = *(n2 + i); *(n2 + i) = tmp; }}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 + size *(j + 1))>0) { swap((char *)base + j*size, (char *)base + size *(j + 1), size); } } }}int main(){ char *arr[] = { "dddd", "aaaa", "bbbb", "cccc" }; int sz = sizeof(arr) / sizeof(arr[0]); bubble(arr, sz, sizeof(char *), str_cmp); int i = 0; for (i = 0; i < sz; i++) { printf("%s\n", arr[i]); } system("pause"); return 0;} 三、冒泡法排序结构体#include<stdio.h>int int_cmp(const void *elem1, const void *elem2){ return (*(int *)elem1 - *(int*)elem2);}int str_cmp(const void *p1, const void *p2){ return strcmp((char *)*(int *)p1, (char *)*(int *)p2);}void swap(char *n1, char *n2, int sz){ int i = 0; for (i = 0; i < sz; i++) { char tmp = *(n1 + i); *(n1 + i) = *(n2 + i); *(n2 + i) = tmp; }}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 + size *(j + 1))>0) { swap((char *)base + j*size, (char *)base + size *(j + 1), size); } } }}typedef struct S{ char name[10]; int age; float score;}S;int S_cmp(const void *elem1, const void *elem2){ return(*(S *)elem1).score - (*(S *)elem2).score;}int main(){ S arr[] = { { "liuyan", 20, 88.0 }, { "wuqian", 23, 93.0 }, { "geshan", 22, 90.0 } }; int sz = sizeof(arr) / sizeof(arr[0]); bubble(arr, sz, sizeof(S), S_cmp); int i = 0; for (i = 0; i < sz; i++) { printf("%s %f\n", arr[i].name, arr[i].score); } system("pause"); return 0;}