当前位置:   article > 正文

数据结构——改进的冒泡排序(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 ;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

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);


}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

这里写图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/824376
推荐阅读
相关标签
  

闽ICP备14008679号