首页 > C语言冒泡排序

C语言冒泡排序

#include <stdio.h>

#define Max  5
int main(int argc, const char * argv[]) {
    int  a[Max] = {22,16,80,1,10};
    int time = 0;
    int count = 0;
    
    for (int i = 0; i < Max - 1 ; i++) {
        for (int j = 0; j < (Max - 1 - i); j++) {
            time++;
            if (a[j] > a[j+1] ) {
                int tmp;
                tmp = a[j];
                a[j] = a[j+1];
                a[j+1] = tmp;
                count++;
            }
        }
    }
    printf("交换次数%d\n",count);
    printf("执行次数%d\n",time);
    //遍历
    for (int i = 0 ; i < Max; i++) {
        printf("%d ",a[i]);
    }
    return 0;
}

Question : 
1.我这已经是最优的了吧
2.第二个for循环的j条件,为什么要设置成 Max - i - 1 ,Max表示数组长度.


1.我这已经是最优的了吧

不是

2.第二个for循环的j条件,为什么要设置成 Max - i - 1 ,Max表示数组长度.

Max - 1- iMax - 1是已经排好序的

objectiv-c是什么鬼


问题 2 的 每次排序,肯定会所最大 的数放到最尾部,所以第二次比较的时候,就不用对最后一位的数进行操作


问题1:这个算法还有一点可以优化,就是对已经有序的序列的处理,比如{1,2,3,5,4};,处理方法是如果没有交换就跳出循环不过我没有完成优化,因为测试过没能完成排序。
问题2:j条件的设置:取决于i的值,因为i之前都是排过序的,还有数组最后一位元素也是排过的。

【热门文章】
【热门文章】