• 微软原版系统

  • 一键重装系统

  • 纯净系统

  • 在线技术客服

魔法猪系统重装大师 一键在线制作启动 U 盘 PE 系统 用一键重装的魔法拯救失去灵魂的系统
当前位置:首页 > 教程 > 电脑教程

C++冒泡排序数据结构、算法及改进算法

时间:2015年04月02日 15:22:02    来源:魔法猪系统重装大师官网    人气:11150

冒泡排序是一种简单排序。这种排序是采用“冒泡策略”将最大元素移到最右边。在冒泡过程中,相邻两个元素比较,如果左边大于右边的,则进行交换两个元素。这样一次冒泡后,可确保最大的在最右边。然后执行n次冒泡后排序即可完毕。

程序代码如下:

// BubbleSort.cpp : 定义控制台应用程序的入口点。

//

#include "stdafx.h"
#include 
#include 
using namespace std;
#define  MAXNUM 20

template
void Swap(T& a, T& b)
{
    int t = a;
    a = b;
    b = t;
}
template
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
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 
#include 
using namespace std;
#define  MAXNUM 20

template
void Swap(T& a, T& b)
{
    int t = a;
    a = b;
    b = t;
}
template
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
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。

C++,冒泡,排序,数据结构,、,算法,及,改进,冒泡,
栏目:电脑教程 阅读:1000 2023/12/27
Win7教程 更多>>
U盘教程 更多>>
Win10教程 更多>>
魔法猪学院 更多>>

Copyright © 2015-2023 魔法猪 魔法猪系统重装大师

本站发布的系统仅为个人学习测试使用,请在下载后24小时内删除,不得用于任何商业用途,否则后果自负,请支持购买微软正版软件。

在线客服 查看微信 返回顶部