牛骨文教育服务平台(让学习变的简单)
博文笔记

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

创建时间:2014-10-07 投稿人: 浏览次数:543
#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;
}

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。