归并排序的递归和非递归实现方法

#include <iostream>
using namespace std;


template<class Type>
void Merge(  Type arr[],  Type dest[], int low, int mid, int high)
{//将有序子段arr[low:mid]和arr[mid+1:high]有序地合并到dest[low:high]中
	int j = mid + 1,
		k = low;
	while (low <= mid && j<= high)
	{
		if (arr[low] < arr[j])
		{
			dest[k++] = arr[low++];
		}
		else
		{
			dest[k++] = arr[j++];
		}
	}

	while (low <= mid)
		dest[k++] = arr[low++];
	while (j <= high)
		dest[k++] = arr[j++];
	
}

template<class Type>
void mergeSort( Type arr[], Type dest[], int low, int high)
{
 	if (low == high)
 		dest[low] = arr[low];
	else
	{
		int mid = (low+high)/2;
		mergeSort(arr, dest, low, mid);
		mergeSort(arr, dest, mid+1, high);
		Merge(arr, dest, low, mid, high);
		//必须重新拷贝回去,这是必须的,《数据结构》没有写是错误的!!
		for (int i=low; i<=high; ++i)
			arr[i] = dest[i];
	}
}

template<class Type>
void NonRecurMergeSort(Type arr[], int low, int high)
{
	Type * dest = new Type[high - low +1];
	int step = 1;//步长
	while (step <= (high - low +1)/2) //while (step < high - low +1) //也是可以的
	{
		MergePass(arr, dest, step, high-low+1);
		step += step;
		MergePass(dest, arr, step, high - low+1);
		step += step;
	}
	delete []dest;
}


template<class Type>
void MergePass(Type arr[], Type dest[], int step, int n)
{//起初的arr[0:n-1],每个长度为step的字段内是有序的,即有n/step个有序的字段。
 //两两合并大小为step的相邻子段,到dest中去
	int i = 0;
	while (i<=n-2*step)
	{
		Merge(arr, dest, i, i+step-1, i+2*step-1);
		i += 2 * step;
	}
	if (i+step <n)
		Merge(arr, dest, i, i+step-1, n-1);
	else
		for(int j=i; j<=n-1; j++)
			dest[j] = arr[j];
}
int main()
{
	int arr[10] = {3, 2, 8, 4, 9, 6, 1, 7, 0, 5};
// 	int brr[10];
// 	mergeSort(arr, brr, 0, 9);
// 	for (int i = 0; i<10; ++i)
// 		cout << brr[i] << " " ;
// 	cout << endl;
	NonRecurMergeSort(arr, 0, 9);
	for (int i = 0; i<10; ++i)
	     cout << arr[i] << " " ;
	cout << endl;

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值