演算法::排序::冒泡排序

來源:互聯網
上載者:User

這應該是最基本的排序演算法了。

具體操作如:

可以看到,該演算法的特點就是像冒泡那樣,不斷把要排序的數往上升。

具體程式如下:

/*用二重迴圈實現,外迴圈變數設為i,內迴圈變數設為j。外迴圈重複9次,內迴圈依次重複9,8,...,1次。每次進行比較的兩個元素都是與內迴圈j有關的,它們可以分別用a[j]和a[j+1]標識,i的值依次為1,2,...,9,對於每一個i, j的值依次為1,2,...10-i。*//*如果有n個數,則要進行n-1趟比較(和交換)。在第1趟中要進行n-1次兩兩比較,在第i趟中要進行n-i次兩兩比較。*/#include <stdio.h>int main(){    int a[10];    int i,j,temp;     printf("please enter ten numbers:\n");    for(i = 0; i < 10; i++)    {    scanf("%d",&a[i]);    }    for(i = 0; i < 9; i++)         //共進行9趟比較    {         for(j = 0; j < 9-i; j++)//在每趟中要進行(10-i)次兩兩比較         {         if(a[j] > a[j+1])            //如果前面一個數比後面的一個數大,就交換兩個數         {             temp = a[j];             a[j] = a[j+1];             a[j+1] = temp;          }     }    }    for(i = 0; i < 10; i++)    {        printf("%d\t",a[i]);    }    printf("\n");    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.