objective-c - C语言冒泡排序
黄舟
黄舟 2017-05-02 09:23:04
0
3
488

#include  #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表示数组长度.
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all (3)
巴扎黑

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

    过去多啦不再A梦

    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 fromMax - 1- iMax - 1

    objectiv-cWhat the hell

      巴扎黑

      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.

        Latest Downloads
        More>
        Web Effects
        Website Source Code
        Website Materials
        Front End Template
        About us Disclaimer Sitemap
        php.cn:Public welfare online PHP training,Help PHP learners grow quickly!