1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| #include <stdio.h>
typedef int KeyType; typedef char InfoType[10];
typedef struct { KeyType key; InfoType data; } RecType;
void DisRecType(RecType R[],int n); void BubbleSort(RecType R[],int n); void BubbleSort_v2(RecType R[],int n); void QuickSort(RecType R[],int left,int right);
int main() { int n = 10; KeyType a[] = {1,4,6,8,0,2,5,7,9,3}; RecType R[10]; for (int i = 0; i < n; i++) R[i].key = a[i];
printf("排序前:"); DisRecType(R,n);
printf("冒泡排序 ... \n"); BubbleSort(R,n);
printf("冒泡排序 改进版 ... \n"); BubbleSort_v2(R,n);
printf("快速排序 ... \n"); QuickSort(R,0,n-1);
printf("排序后:"); DisRecType(R,n); }
void DisRecType(RecType R[],int n) { for (int i = 0; i < n; i++) printf("%d ",R[i].key);
printf("\n"); }
void BubbleSort(RecType R[],int n) { int i,j; RecType tmp; for (i = 0; i < n-1; i++) { for (j = n-1; j > i; j--) { if (R[j-1].key > R[j].key) { tmp = R[j-1]; R[j-1] = R[j]; R[j] = tmp; } } printf("%d \n",i); } }
void BubbleSort_v2(RecType R[],int n) { int i,j; RecType tmp; for (i = 0; i < n-1; i++) { int flag = 1; for (j = n-1; j > i; j--) { if (R[j-1].key > R[j].key) { tmp = R[j-1]; R[j-1] = R[j]; R[j] = tmp;
flag = 0; } } printf("%d \n",i); if (flag) break; } }
void QuickSort(RecType R[],int left,int right) { int i = left; int j = right; RecType tmp;
if (left >= right) return; tmp = R[i]; while (i < j) { while (i < j && R[j].key >= tmp.key) j--; R[i] = R[j]; while (i < j && R[i].key <= tmp.key) i++; R[j] = R[i]; }
R[i] = tmp; QuickSort(R,left,i-1); QuickSort(R,i+1,right); }
|