数据结构——改进的冒泡排序(c++)

ImprovedBubbleSorter.h

//ImprovedBubbleSorter.h
//优化的起泡排序类
#include "Sorter.h"

template <class Record>
class ImprovedBubbleSorter:public Sorter<Record>
{
public:
    void Sort(Record Array[],int n);
};

//优化的起泡排序,Array[]为待排序数组,n为数组长度
template <class Record>
void ImprovedBubbleSorter<Record>::Sort(Record Array[], int n) 
{ 
    bool NoSwap;
    int i,j;
    for(i=0;i<n-1;i++)
    {
        NoSwap=true;
        for(j=n-1;j>i;j--)
        {
            if(Array[j]<Array[j-1])
            {
                swap(Array,j,j-1);
                NoSwap=false;
            }
        }
        if(NoSwap)
            return ;
    }
}

Sorter.h

//Sorter.h
#if !defined(AFX_Sorter)
#define AFX_Sorter

//总排序类
template <class Record>
class Sorter{
protected:
    static void swap(Record Array[],int i,int j);   //交换数组中的两个记录
public:
    virtual void Sort(Record Array[],int n)=0;          //对数组Array进行排序
    void PrintArray(Record array[], int n);     //输出数组内容
};

//交换数组中的两个记录
template <class Record>
void Sorter<Record>::swap(Record Array[],int i,int j)
{
    Record TempRecord = Array[i];
    Array[i] = Array[j];
    Array[j] = TempRecord;

}

//输出数组内容
template <class Record>
void Sorter<Record>::PrintArray(Record Array[], int n)
{
    for(int i=0;i<n;i++)
        cout<<Array[i]<<" ";
    cout<<endl;
}  

#endif

ImprovedBubbleSort.cpp

//ImprovedBubbleSort.cpp
//优化的起泡排序

#include <iostream.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "ImprovedBubbleSorter.h"
const int N=1000;
// 设定随即函数的种子
inline void Randomize() 
  { srand(1); }

//返回一个0到n-1之间的随机数
inline int Random(int n)
  { return rand() % (n); }

void main()
{
    ImprovedBubbleSorter<int> s;
    int Array[8];
    for(int i=0;i<8;i++)
    {
        Array[i]=Random(10);
    }
    s.Sort(Array,8); 
    s.PrintArray(Array,8);


}

这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值