StraightSelectSorter.h
//StraightSelectSorter.h
//直接选择排序类
#include "Sorter.h"
template <class Record>
class StraightSelectSorter:public Sorter<Record>
{
public:
void Sort(Record Array[],int n);
};
//直接选择排序,Array[]为待排序数组,n为数组长度
template <class Record>
void StraightSelectSorter<Record>::Sort(Record Array[], int n)
{
int i,j,Smallest;
for(i=0;i<n-1;i++)
{
Smallest=i;
for(j=i+1;j<n;j++)
{
if(Array[j]<Array[Smallest])
{
Smallest=j;
}
}
swap(Array,i,Smallest);
}
}
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
StraightSelectSort.cpp
//StraightSelectSort.cpp
//直接选择排序
#include <iostream.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "StraightSelectSorter.h"
const int N=1000;
// 设定随即函数的种子
inline void Randomize()
{ srand(1); }
//返回一个0到n-1之间的随机数
inline int Random(int n)
{ return rand() % (n); }
void main()
{
StraightSelectSorter<int> s;
int Array[8];
for(int i=0;i<8;i++)
{
Array[i]=Random(1000);
}
s.Sort(Array,8);
s.PrintArray(Array,8);
}