C++ 冒泡排序資料結構、演算法及改進演算法

來源:互聯網
上載者:User

程式碼如下:

複製代碼 代碼如下:// BubbleSort.cpp : 定義控制台應用程式的進入點。
//
#include "stdafx.h"
#include <cmath>
#include <iostream>
using namespace std;
#define MAXNUM 20
template<typename T>
void Swap(T& a, T& b)
{
int t = a;
a = b;
b = t;
}
template<typename T>
void Bubble(T a[], int n)
{//把數組a[0:n-1]中最大的元素通過冒泡移到右邊
for(int i =0 ;i < n-1; i++)
{
if(a[i] >a[i+1])
Swap(a[i],a[i+1]);
}
}
template<typename T>
void BubbleSort(T a[],int n)
{//對數組a[0:n-1]中的n個元素進行冒泡排序
for(int i = n;i > 1; i--)
Bubble(a,i);
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[MAXNUM];
for(int i = 0 ;i< MAXNUM; i++)
{
a[i] = rand()%(MAXNUM*5);
}
for(int i =0; i< MAXNUM; i++)
cout << a[i] << " ";
cout << endl;
BubbleSort(a,MAXNUM);
cout << "After BubbleSort: " << endl;
for(int i =0; i< MAXNUM; i++)
cout << a[i] << " ";
cin.get();
return 0;
}

但是常規的冒泡,不管相鄰的兩個元素是否已經排好序,都要冒泡,這就沒有必要了,所有我們對這點進行改進。設計一種及時終止的冒泡排序演算法:

如果在一次冒泡過程中沒有發生元素互換,則說明數組已經按序排列好了,沒有必要再繼續進行冒泡排序了。代碼如下:

複製代碼 代碼如下:// BubbleSort.cpp : 定義控制台應用程式的進入點。

//
#include "stdafx.h"
#include <cmath>
#include <iostream>
using namespace std;
#define MAXNUM 20
template<typename T>
void Swap(T& a, T& b)
{
int t = a;
a = b;
b = t;
}
template<typename T>
bool Bubble(T a[], int n)
{//把數組a[0:n-1]中最大的元素通過冒泡移到右邊
bool swapped = false;//尚未發生交換
for(int i =0 ;i < n-1; i++)
{
if(a[i] >a[i+1])
{
Swap(a[i],a[i+1]);
swapped = true;//發生了交換
}
}
return swapped;
}
template<typename T>
void BubbleSort(T a[],int n)
{//對數組a[0:n-1]中的n個元素進行冒泡排序
for(int i = n;i > 1 && Bubble(a,i); i--);
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[MAXNUM];
for(int i = 0 ;i< MAXNUM; i++)
{
a[i] = rand()%(MAXNUM*5);
}
for(int i =0; i< MAXNUM; i++)
cout << a[i] << " ";
cout << endl;
BubbleSort(a,MAXNUM);
cout << "After BubbleSort: " << endl;
for(int i =0; i< MAXNUM; i++)
cout << a[i] << " ";
cin.get();
return 0;
}

改進後的演算法,在最壞的情況下執行的比較次數與常規冒泡一樣,但是最好情況下次數減少為n-1。

相關文章

聯繫我們

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