search

Home  >  Q&A  >  body text

objective-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表示数组长度.

黄舟黄舟2758 days ago532

reply all(3)I'll reply

  • 巴扎黑

    巴扎黑2017-05-02 09:25:04

    For question 2, every time you sort, the largest number will definitely be placed at the end, so during the second comparison, there is no need to operate on the last number

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-02 09:25:04

    1. This is already the best for me

    No

    2. Why should the j condition of the second for loop be set to Max - i - 1? Max represents the length of the array.

    It is already sorted from Max - 1- iMax - 1

    objectiv-cWhat the hell

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-02 09:25:04

    Question 1: There is another point that can be optimized in this algorithm, which is the processing of already ordered sequences, such as {1, 2, 3, 5, 4};. The processing method is to jump out of the loop if there is no exchange. However, I have not completed the optimization. , because the sorting could not be completed after testing.
    Question 2: The setting of j condition: depends on the value of i, because i has been sorted before, and the last element of the array has also been sorted.

    reply
    0
  • Cancelreply