1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <time.h> 4 5 #define MAXLENGTH 21 6 7 typedef struct 8 { 9 int key; 10 } Record; 11 12 typedef struct 13 { 14 Record r[MAXLENGTH]; 15 int length; 16 } DataList; 17 18 void printList(DataList *list) 19 { 20 int i = 0; 21 for(i-0; i<list->length; i++) 22 { 23 printf("%d ",list->r[i]); 24 } 25 printf("\n"); 26 } 27 28 void bubble_sort(DataList *list) 29 { 30 int i=0; 31 int j = 0; 32 33 for (i=1; i<list->length; i++) 34 { 35 for(j=1; j<list->length-i; j++) 36 { 37 if(list->r[j].key>list->r[j+1].key) 38 { 39 list->r[0] = list->r[j+1]; 40 list->r[j+1] = list->r[j]; 41 list->r[j] = list->r[0]; 42 } 43 } 44 } 45 } 46 47 int main() 48 { 49 DataList *list = (DataList *)malloc(1*sizeof(DataList)); 50 memset(list,0,sizeof(DataList)); 51 52 srand(time(0)); 53 54 int m = 0; 55 int index = 1; 56 for(m=0; m<20; m++) 57 { 58 int i = 0; 59 i = rand() % 100; 60 list->r[index].key = i; 61 list->length++; 62 index++; 63 } 64 65 printList(list); 66 67 bubble_sort(list); 68 69 printList(list); 70 }
c语言实现冒泡排序