1. 程式人生 > >插入排序的三種形式所需時間

插入排序的三種形式所需時間

#include<bits/stdc++.h>
#define M 10010
#define mod 10000
using namespace std;
typedef int KeyType;
typedef int InfoType;
int dt[13] = {5000,2500,1250,625,313,157,79,40,20,10,5,2,1};

typedef struct
{
	KeyType key;
	InfoType otherinfo;
}RedType;

typedef struct
{
	RedType *r;
	int length;
}SqList;

void begin(SqList &L)
{
	L.r = new RedType[M];
	L.length = 10000;
	srand((unsigned)time(NULL));
	for (int i=1;i<=L.length;i++)
		L.r[i].key = rand() % mod;
}

void InsertSort(SqList &L)
{
	int i,j;
	for (i=2;i<=L.length;i++)
	{
		if (L.r[i].key<L.r[i-1].key)
		{
			L.r[0] = L.r[i];
			L.r[i] = L.r[i-1];
			for (j=i-2;L.r[0].key<L.r[j].key;j--)
				L.r[j+1] = L.r[j];
			L.r[j+1] = L.r[0];
		}
	}
}

void BInsertSort(SqList &L)
{
	int i,j;
	for (i=2;i<=L.length;i++)
	{
		L.r[0] = L.r[i];
		int low = 1,high = i - 1;
		while (low<=high)
		{
			int m = (low + high) / 2;
			if (L.r[0].key<L.r[m].key)
				high = m - 1;
			else low = m + 1;
		}
		for (j=i-1;j>=high+1;j--)
			L.r[high+1] = L.r[j];
		L.r[high+1] = L.r[0];
	}
}

void ShellInsert(SqList &L,int dk)
{
	int i,j;
	for (i=dk+1;i<=L.length;i++)
	{
		if (L.r[i].key<L.r[i-dk].key)
		{
			L.r[0] = L.r[i];
			for (j=i-dk;j>0 && L.r[0].key<L.r[j].key;j-=dk)
				L.r[j+dk] = L.r[j];
			L.r[j+dk] = L.r[0];
		}
	}
}

void ShellSort(SqList &L,int dt[],int t)
{
	for (int k=0;k<t;k++)
		ShellInsert(L,dt[k]);
}

int main()
{
	int i,j;
	SqList L1,L2,L3;
	int begintime,endtime;
	/*---------------直接插入排序-------------------*/
	begin(L1);
	begintime = clock();
	InsertSort(L1);	
	endtime = clock();
	printf("\n\nInsertSort Running Time:%dms\n", endtime-begintime);
	/*---------------折半插入排序-------------------*/
	begin(L2);
	begintime = clock();
	BInsertSort(L2);
	endtime = clock();
	printf("\n\nBInsertSort Running Time:%dms\n", endtime-begintime);
	/*----------------希爾排序----------------------*/
	begin(L3);
	begintime=clock();
	ShellSort(L3,dt,13);
	endtime = clock();
	printf("\n\nShellSort Running Time:%dms\n", endtime-begintime);
	return 0;
}