冒泡排序法的機理和實現

來源:互聯網
上載者:User

 冒泡排序(BubbleSort)的基本概念是:依次比較相鄰的兩個數,將小數放在前面,大數放在後面。即在第一趟:首先比較第1個和第2個數,將小數放前,大數放後。然後比較第2個數和第3個數,將小數放前,大數放後,如此繼續,直至比較最後兩個數,將小數放前,大數放後。至此第一趟結束,將最大的數放到了最後。在第二趟:仍從第一對數開始比較(因為可能由於第2個數和第3個數的交換,使得第1個數不再小於第2個數),將小數放前,大數放後,一直比較到倒數第二個數(倒數第一的位置上已經是最大的),第二趟結束,在倒數第二的位置上得到一個新的最大數(其實在整個數列中是第二大的數)。如此下去,重複以上過程,直至最終完成排序。 

#include <iostream>
#include <time.h>
using namespace std;
#define N 15
int main()
{
 int a[N];
 int i, j, temp;
 srand(time(0));
 for (i = 0; i < N; i++)
 {
  a[i] = rand();
 }
 int flag = 1;
 for (i = 0; i < N - 1 && flag == 1; i++)
 {
  flag = 0;
  for (j = 0; j < N - i - 1; j++)
  {
   if (a[j + 1] < a[j])
   {
    temp = a[j + 1];
    a[j + 1] = a[j];
    a[j] = temp;
    flag = 1;
   }
  }
 }
 for (i = 0; i < N; i++)
 {
  cout<<a[i]<<'\t';
 }
 return 0;
}

 

 

用c++模板演算法實現

#include <iostream>
#include<vector>
#include<algorithm>
#include <time.h>
using namespace std;

int main()
{
 const int N  = 15;
 vector<int>vec_int;

 srand(time(0));
 for (int i = 0; i < N; i++)
 {
  int num =  rand();
  vec_int.push_back(num);
 }
 sort(vec_int.begin(), vec_int.end());

 for (int j = 0; j < N; j++)
 {
  cout<<vec_int[j]<<'\t';
 }
 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.