實現排序表的抽象數據類型,可以隨機生成n(5000<=n<=50000)個待排序數據。
#include<iostream>
#include<stdlib.h>
#include"assert.h"
#include<time.h>
using namespace std;
template<class type>
struct SqList{
type * key;
int length;
};
template<class type>
void CreateSqList(SqList<type> &sl)//type爲int
{
int n=1;
srand((int)time(0));
while(n<5000||n>50000)
{
n=rand()%50000;
}
sl.length=n;
sl.key=new int[sl.length+1];
assert(sl.key);
for(int i=0;i<sl.length;i++)
{
sl.key[i]=rand()%100;
}
}
template<class type>
void OutPut(SqList<type> &L)
{
for(int j=0;j<L.length;j++)
cout<<L.key[j]<<"\t";
cout<<endl;
}
template<class type>
void InsertSort(SqList<type> & L)
{//對順序表L作直接插入排序
for(int i=1;i<L.length;i++)//用i控制比較趟數共n-1趟
{
type t;
for(int j=1;j<=L.length-i;j++)
if(L.key[j]>L.key[j+1])
{
t=L.key[j];
L.key[j]=L.key[j+1];
L.key[j+1]=t;
}
}
}
int main()
{
SqList<int> sl;
CreateSqList(sl);
InsertSort(sl);
cout<<"直接插入排序結果如下:"<<endl;
OutPut(sl);
delete sl.key;
}