排序小练

实现排序表的抽象数据类型,可以随机生成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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值