首页 > 代码库 > 冒泡排序较优解

冒泡排序较优解

 1 #include <stdio.h>
 2 
 3 void swap(int *a,int *b);
 4 int main(int argc, const char * argv[]) {
 5     
 6     int a[6] = {1,6,8,1,6,8};
 7     int length = sizeof(a)/sizeof(a[0]);
 8     _Bool flag = 1;
 9     
10     for (int i=1; i<length && flag; i++) {
11         
12         flag = 0;
13         for (int j=length-1; j>=i; j--) {
14             if (a[j-1]>a[j]) {
15                 swap(&a[j-1], &a[j]);
16                 flag = 1;
17             }
18         }
19     }
20     
21     for (int i = 0; i<length; i++) {
22         printf("%d\t",a[i]);
23     }
24     printf("\n");
25     return 0;
26 }
27 
28 void swap(int *a,int *b){
29     int temp = *a;
30     *a = *b;
31     *b = temp;
32 }

 

冒泡排序较优解