C語言程式設計 冒泡排序簡介

來源:互聯網
上載者:User
冒泡排序基本思想
將n個記錄看作按縱向排列,每趟排序時自下至上對每對相鄰記錄進行比較,若次序不符合要求(逆序)就交換。每趟排序結束時都能使排序範圍內關鍵字最小的記錄象一個氣泡一樣升到表上端的對應位置,整個排序過程共進行n-1趟,依次將關鍵字最小、次小、第三小…的各個記錄“冒到”表的第一個、第二個、第三個…位置上。

   初態      第1趟   第2趟  第3趟  第4趟  第5趟  第6趟  第7趟
    38        12      12      12      12      12      12      12                              
    20        38      20      20      20      20      20      20
    46        20      38      25      25      25      25      25
    38        46      25      38      38      38      38      38
    74        38      46      38      38      38      38      38
    91        74      38      46      46      46      46      46
    12        91      74      74      74      74      74      74
    25        25      91      91      91      91      91      91

/*
Title:  冒泡排序
Author: Li Aimin
Date: May 2007
演算法功能:冒泡排序演算法實現將一個長度為n的線性表r上的所有元素按關鍵字升序排列。
*/
#include<stdio.h>

void bubblesort(int r[],int n)
 { /*elements are stored in r[1] to r[n]*/
  int i,j,flag;
  int temp;
  flag=1;
  i=1;
  while((i<n)&&(flag==1)) /*外迴圈控制排序的總趟數*/
   {  flag=0;
      for(j=n;j>i;j--) /*內迴圈控制一趟排序的進行*/
          if(r[j]<r[j-1])  /*相鄰元素進行比較,若逆序就交換*/
           {
          flag=1;
              temp=r[j];
              r[j]=r[j-1];
              r[j-1]=temp;
           }
      i++;
    }
} /*bubblesort*/

void show(int  r[] , int n)
{
  /*elements are stored in r[1] to r[n]*/
  int i;
  for(i=1;i<=n;i++)
   printf(" %d ",r[i]);
  printf("\n");

}

void main()
{
 int a[9201],i;
 for(i=0;i<9201;i++)
     a[i]=9201-i;
 //show(a,100000);
 bubblesort(a,9200);
 show(a,9200);
}

相關文章

聯繫我們

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