合并排序(递归分治 + 泛型)

时间:2022-07-17 11:07:43


#include<iostream>
using namespace std;

//将a[left : right]中的所有元素合并排序
template<class Type>
void MergeSort(Type a[],int left,int right)
{
	if(left < right)   //当相等的时候已经只剩下一个元素了,可以结束了
	{
		int n = right + 1; //分配的内存数目够了,但是还要记得能否索引到
		Type* b = new Type[n];  //动态分配一段缓存
		int middle = (left + right)/2;
		MergeSort(a,left,middle);
		MergeSort(a,middle+1,right);
		Merge(a,b,left,middle,right);
		Copy(a,b,left,right);
		delete[] b;
	}
}

//将c[left : middle]和c[middle+1 : rught]合并到d[left : right]中
template<class Type>
void Merge(Type c[],Type d[],int left,int middle,int right)
{                      
	int i = left,j = middle + 1,k = left;
	while((i <= middle)&&(j <= right))
	{
		if(c[i] <= c[j])
			d[k++] = c[i++];
		else
			d[k++] = c[j++];
	}
	
	if(i > middle)
	{
		for(int q = j;q <= right;q++)
			d[k++] = c[q];
	}
	else
	{
		for(int q = i;q <= middle;q++)
			d[k++] = c[q];
	}
}

//将b[left : right]中的所有元素拷贝到a[left : right]中
template<class Type>
void Copy(Type a[],Type b[],int left,int right)
{
	while(left <= right)
	{
		a[left] = b[left];
		left++;
	}
}


void main()
{
	char a[] = {'b','c','a','d','f','e','g','j','h','s','q','p','o','r','u','k','g'};
	//int a[] = {2,1,4,6,5,4,7,8,34,2,345,5,34,2,1,0,23,5,4,5,4};
	//int a[] = {4,3,5,6,7,2,1};
	MergeSort(a,0,sizeof(a)/sizeof(a[0]) - 1);
	for(int i = 0;i < sizeof(a)/sizeof(a[0]);i++)
		cout<<a[i]<<" ";
	cout<<endl;
}

/*
a b c d e f g g h j k o p q r s u
*/