C++ 冒泡排序數(shù)據(jù)結(jié)構(gòu)、算法及改進算法
程序代碼如下:
// BubbleSort.cpp : 定義控制臺應(yīng)用程序的入口點。
//
#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)
{//把數(shù)組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)
{//對數(shù)組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;
}
但是常規(guī)的冒泡,不管相鄰的兩個元素是否已經(jīng)排好序,都要冒泡,這就沒有必要了,所有我們對這點進行改進。設(shè)計一種及時終止的冒泡排序算法:
如果在一次冒泡過程中沒有發(fā)生元素互換,則說明數(shù)組已經(jīng)按序排列好了,沒有必要再繼續(xù)進行冒泡排序了。代碼如下:
// BubbleSort.cpp : 定義控制臺應(yīng)用程序的入口點。
//
#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)
{//把數(shù)組a[0:n-1]中最大的元素通過冒泡移到右邊
bool swapped = false;//尚未發(fā)生交換
for(int i =0 ;i < n-1; i++)
{
if(a[i] >a[i+1])
{
Swap(a[i],a[i+1]);
swapped = true;//發(fā)生了交換
}
}
return swapped;
}
template<typename T>
void BubbleSort(T a[],int n)
{//對數(shù)組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;
}
改進后的算法,在最壞的情況下執(zhí)行的比較次數(shù)與常規(guī)冒泡一樣,但是最好情況下次數(shù)減少為n-1。
- C++數(shù)據(jù)結(jié)構(gòu)與算法之哈夫曼樹的實現(xiàn)方法
- C++數(shù)據(jù)結(jié)構(gòu)與算法之反轉(zhuǎn)鏈表的方法詳解
- C++數(shù)據(jù)結(jié)構(gòu)與算法之雙緩存隊列實現(xiàn)方法詳解
- C++ 數(shù)據(jù)結(jié)構(gòu)之kmp算法中的求Next()函數(shù)的算法
- C++ 數(shù)據(jù)結(jié)構(gòu)之水洼的數(shù)量算法
- C++數(shù)據(jù)結(jié)構(gòu)與算法之判斷一個鏈表是否為回文結(jié)構(gòu)的方法
- C++數(shù)據(jù)結(jié)構(gòu)與算法的基礎(chǔ)知識和經(jīng)典算法匯總
相關(guān)文章
C語言將數(shù)組中元素的數(shù)排序輸出的相關(guān)問題解決
這篇文章主要介紹了C語言將數(shù)組中元素的數(shù)排序輸出的相關(guān)問題解決,文中的題目是將元素連接起來排成一個數(shù)并要求出這類結(jié)果中數(shù)最小的一個,需要的朋友可以參考下2016-03-03OpenMP task construct 實現(xiàn)原理及源碼示例解析
這篇文章主要為大家介紹了OpenMP task construct 實現(xiàn)原理及源碼示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03Linux環(huán)境g++編譯GDAL動態(tài)庫操作方法
下面小編就為大家?guī)硪黄狶inux環(huán)境g++編譯GDAL動態(tài)庫操作方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05C語言實現(xiàn)簡單學(xué)生學(xué)籍管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C語言實現(xiàn)簡單學(xué)生學(xué)籍管理系統(tǒng),具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-01-01