經典排序之冒泡排序

來源:互聯網
上載者:User

標籤:經典   冒泡排序   

核心代碼:

/*冒泡排序

     未經處理資料: 28, 30, 19, 2, 23

     第一趟:

           第一次:28, 30, 19, 2, 23

           第二次:28, 19, 30, 2, 23

           第三次:28, 19, 2, 30, 23

           第四次:28, 19, 2, 23, 30

     第二趟:

           第一次:19, 28, 2, 23, 30

           第二次:19, 2, 28, 23, 30

           第三次:19, 2, 23, 28, 30

     第三趟:

           第一次:2, 19, 23, 28, 30

           第二次:2, 19, 23, 28, 30

     第四趟:

           第一次:2, 19, 23, 28, 30

     */

    //n個元素比較n-1趟

    //每趟比較次數 = 數組元素個數 - 趟數

//給定一個數組

//    int a[5] = {7, 2, 3, 4 ,5};

//    for (int i = 0; i < 5 - 1; i++) {          //比較的趟數

//        for (int j = 0; j < 5 - 1 - i; j++) {  //每趟比較的次數

//            if (a[j] > a[j+1]) {

//                int temp = a[j];

//                a[j] = a[j + 1];

//                a[j + 1] = temp;

//            }

//        }

//    }

//    printf("從小到大排序為:");

//    for (int i = 0; i < 5; i++) {

//        printf("%d  ", a[i]);

//    }

    //隨機產生一組20個元素的數組取值範圍為[20, 40]

    int a[20] = {0};

    printf("隨機產生的一個包含20個元素的數組:\n");

    for (int i = 0; i < 20; i++) {

        a[i] = arc4random()%(40 - 20 + 1) + 20; //arc4random產生隨機數

        printf("%d  ", a[i]);

    }

    for (int i = 0; i < 20 - 1; i++) {              //比較的趟數

        for (int j = 0; j < 20 - 1 - i; j++) {     //每趟比較的次數

            if (a[j] > a[j + 1]) {

                int temp = a[j];

                a[j] = a[j + 1];

                a[j + 1] = temp;

            }

        }

    }

    printf("\n進行冒泡排序,產生一組從小到大順序的數組:\n");

    for (int i = 0; i < 20; i++) {

        printf("%d  ", a[i]);

    }


本文出自 “經典排序冒泡排序” 部落格,請務必保留此出處http://summerios.blog.51cto.com/9167658/1440138

經典排序之冒泡排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.