冒泡排序C语言版:在每轮排序中检查时候有元素位置交换,如果无交换,说明数组元素已经有序,无需继续排序
1 #include <stdio.h> 2 #include <stdlib.h> 3 void bubble_sort(int array[], int n) 4 { 5 for(int i = 0; i < n-1; ++i) 6 { 7 printf("-------%d------- ",i); 8 int changeFlag = false; 9 for(int j = 0; j<n-1-i; ++j) 10 { 11 if(array[j]>array[j+1]) 12 { 13 int temp = array[j]; 14 array[j] = array[j+1]; 15 array[j+1] = temp; 16 changeFlag = true; 17 } 18 } 19 if(changeFlag == false) 20 { 21 break; 22 } 23 } 24 } 25 26 int main() { 27 int number[10] = {95, 45, 15, 78, 84, 51, 24, 12, 38, 97}; 28 int i,SIZE=10; 29 bubble_sort(number, SIZE); 30 for (i = 0; i < SIZE; i++) 31 { 32 printf("%d, ", number[i]); 33 } 34 printf(" "); 35 return 0; 36 }