国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

C++ 冒泡排序數據結構、算法及改進算法

2020-01-26 16:19:06
字體:
來源:轉載
供稿:網友

程序代碼如下:

復制代碼 代碼如下:

// 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。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 株洲市| 珲春市| 曲松县| 柳林县| 汤原县| 丹江口市| 夏邑县| 朝阳区| 鸡东县| 永城市| 连城县| 沙洋县| 宜黄县| 四子王旗| 商都县| 白朗县| 夏津县| 女性| 凭祥市| 鄂伦春自治旗| 襄城县| 且末县| 南丰县| 会泽县| 三河市| 新平| 宁城县| 交口县| 务川| 宁安市| 大庆市| 石景山区| 太和县| 云霄县| 株洲县| 灵丘县| 桂东县| 汝阳县| 织金县| 承德市| 漳平市|