插入排序,选择排序,Shell排序

实现基于数组的插入排序,选择排序,Shell排序。

插入排序,特点是移动次数多。

void InsertSort(int* start, int size)
{
	int temp=0;
	for(int i=1;i<size;++i)
	{
		temp = start[i];
		int position = i;
		for( ; position > 0; --position)
		{
			if( temp < start[position - 1])
				start[position] = start[position -1];
			else
				break;
		}
		start[position] = temp;
	}
}

选择排序,相对选择排序,使用了相对较少的移动次数,但是比较次数很多。

void SelectSort(int* start, int size)
{
	for(int i=size-1;i>0;--i)
	{
		int largest = 0;
		for(int j=1; j<= i; ++j)
		{
			if(start[largest] < start[j])
				largest = j;
		}

		if( largest != i )
		{
			int temp = start[i];
			start[i] = start[largest];
			start[largest] = temp;
		}
	}
}


Shell排序,是对插入排序的一种改善,采用不同的插入排序的步长,可以将插入排序的移动次数减少。步长不要选择2的幂的数列,比如8,4,2,1,以避免重复排序。

void ShellSort(int* start, int size)
{
	int step = size;
	do
	{
		step = step / 3 + 1;
		for(int i=0;i<step;++i)
			ShellInsertSort(start+i,size-i,step);
	}while(step > 1);
}

void ShellInsertSort(int* start,int size,int step)
{
	int temp =0;
	for(int i=step;i<size;i+=step)
	{
		temp = start[i];
		int position = i;
		for( ; position > 0; position-=step)
		{
			if( temp < start[position - step])
				start[position] = start[position -step];
			else
				break;
		}
		start[position] = temp;
	}
}


如下是测试代码:

void TestSort(int number,int max,string tag ,void (*SortFunc)(int*,int))
{
	srand(time(NULL));
	int* list = new int[number];
	for(int i=0;i<number;++i)
		list[i] = GenerateRandomNumber(max);

	DoTestSort(tag,list,number,SortFunc);
}

void TestSort(int number,int max)
{
	TestSort(number,max,"Insert Sort",InsertSort);
	TestSort(number,max,"Select Sort",SelectSort);
	TestSort(number,max,"Shell Sort",ShellSort);
}

void DoTestSort(string tag, int* list,int size, void (*SortFunc)(int*,int))
{
	cout << tag << " test" << endl;
	PrintList(list,size);
	SortFunc(list,size);
	cout << "IsInOrder=" << IsInOrder(list,size) << endl;
	PrintList(list,size);
}

int GenerateRandomNumber(int max)
{
	return rand() % max + 1;
}

void PrintList(int* start, int size)
{
	for(int i=0;i<size;++i)
		cout<< start[i] << ",";
	cout << endl;
}

bool IsInOrder(int* start, int size)
{
	for(int i=0;i<size-1;++i)
	{
		if(start[i] > start[i+1])
			return false;
	}
	return true;
}


还有一个简单的类似排序,冒泡排序,代码如下:

void PopSort(int* pData,int length)
{
	bool change = true;
	int temp = 0;
	for(int i=0;i<length-1 && change;++i)
	{
		change = false;
		for(int k=length-1;k>i;--k)
		{
			if(pData[k] < pData[k-1])
			{
				temp = pData[k];
				pData[k] = pData[k-1];
				pData[k-1] = temp;
				change = true;
			}
		}
	}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值