栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

程序代码如下:
复制代码 代码如下:
// 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。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/66796.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号