冒泡排序的主要过程:
- 比较相邻的元素。如果第一个比第二个大,就交换他们两个。
- 对每一对相邻元素做同样的工作,从开始第一对到结尾的最后一对。比较一趟之后,最后的元素应该会是最大的数。
- 针对所有的元素重复以上的步骤,除了最后一个。
- 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 int n; 5 6 /* 7 * 冒泡排序 8 */ 9 void BubbleSort(int *array) 10 { 11 int i, j, temp; 12 for (i = 0; i < n - 1; i++) 13 { 14 for (j = 0; j < n - 1 - i; j++) 15 { 16 if (array[j] > array[j + 1]) 17 { 18 temp = array[j]; 19 array[j] = array[j + 1]; 20 array[j + 1] = temp; 21 } 22 } 23 } 24 } 25 26 int main() 27 { 28 int i; 29 int *array; 30 printf("请输入数组的大小:"); 31 scanf("%d", &n); 32 array = (int*) malloc(sizeof(int) * n); 33 printf("请输入数据(用空格分隔):"); 34 for (i = 0; i < n; i++) 35 { 36 scanf("%d", &array[i]); 37 } 38 BubbleSort(array); 39 printf("排序后为:"); 40 for (i = 0; i < n; i++) 41 { 42 printf("%d ", array[i]); 43 } 44 printf(" "); 45 }