1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <time.h> 4 #define MAX 10 5 6 void selsort(int[]); 7 void bubsort(int[],int); 8 void insort(int[]); 9 void bubsort(int[]); 10 void swap(int &, int &); 11 int prin(int[]); 12 int main() 13 { 14 int number[MAX] = { 0 }; 15 int i; 16 srand(time(NULL)); 17 printf("排序前: "); 18 for (i = 0; i < MAX; i++) 19 { 20 number[i] = rand() % 100; 21 printf("%d ", number[i]); 22 } 23 printf("\n请选择排序方式: \n"); 24 printf("1:选择\n2:冒泡\n3:插入\n4:没有flag的冒泡:"); 25 scanf_s("%d", &i); 26 switch (i) 27 { 28 case 1: 29 selsort(number); 30 break; 31 case 2: 32 bubsort(number,1); 33 break; 34 case 3: 35 insort(number); 36 break; 37 case 4: 38 bubsort(number); 39 break; 40 default: 41 printf("只有这四种可选\n"); 42 } 43 return 0; 44 } 45 void swap(int &x, int &y) 46 { 47 int t; 48 t = x; 49 x = y; 50 y = t; 51 } 52 void selsort(int number[]) 53 { 54 int i, j, k, m; 55 for (i = 0; i < MAX - 1; i++) 56 { 57 m = i; 58 for (j = i + 1; j < MAX; j++) 59 { 60 if (number[j] < number[m]) 61 m = j; 62 } 63 64 if (i != m) 65 swap(number[i], number[m]); 66 printf("第%d次选择排序: ", i + 1); 67 for (k = 0; k < MAX; k++) 68 { 69 printf("%d ", number[k]); 70 } 71 72 printf("\n"); 73 } 74 } 75 void bubsort(int number[],int flag) 76 { 77 int i, j, k; 78 for (i = 0; i < MAX - 1 && flag==1; i++) 79 { 80 flag = 0; 81 for (j = 0; j < MAX - (i + 1); j++) 82 { 83 if (number[j + 1] < number[j]) 84 { 85 swap(number[j + 1], number[j]); 86 flag = 1; 87 } 88 } 89 printf("第%d次冒泡排序:", i + 1); 90 prin(number); 91 } 92 } 93 void bubsort(int number[]) 94 { 95 int i, j, k; 96 for (i = 0; i < MAX - 1; i++) 97 { 98 for (j = 0; j < MAX - (i + 1); j++) 99 { 100 if (number[j + 1] < number[j]) 101 { 102 swap(number[j + 1], number[j]); 103 } 104 } 105 printf("第%d次没有flag冒泡排序:", i + 1); 106 prin(number); 107 } 108 } 109 void insort(int number[]) 110 { 111 int i, j, k, tmp; 112 for (j = 1; j < MAX - 1; j++) 113 { 114 tmp = number[j]; 115 i = j - 1; 116 while (tmp < number[i]) 117 { 118 number[i + 1] = number[i]; 119 i--; 120 if (i == -1) 121 break; 122 } 123 number[i + 1] = tmp; 124 printf("第%d次插入排序:", i + 1); 125 prin(number); 126 } 127 } 128 int prin(int number[]) 129 { 130 int i; 131 for (i = 0; i < MAX; i++) 132 { 133 printf("%d ", number[i]); 134 } 135 printf("\n"); 136 return 0; 137 }
对于flag的解释引用知乎上截图
有flag 但还是会多一次重复的排序。