递归合并排序

#include<iostream>
using namespace std;
#include<stdio.h>


int b[5];
template<class Type>
void Merge(Type c[],Type d[],int l,int m,int r){

	int i = l,j = m+1,k = l;
	while( (i <= m) && (j <= r) )
	{
		if(c[i] <= c[j])
			d[k++] = c[i++];
		else
			d[k++] = c[j++];
	}
		if(i > m)
		
			for(int q = j;q <= r;q++)
				d[k++] = c[q];
			else
				for(int q=i;q<=m;q++)
				d[k++] = c[q];
		

			for(int q = l;q <= r;q++)
				c[q] = d[q];

}

template<class Type>
void MergeSort(Type a[],int left,int right){
	if(left < right){//至少有2个元素
		int i = (left + right)/2;
		MergeSort(a,left,i);
		MergeSort(a,i+1,right);
		Merge(a,b,left,i,right);
	}
	else return;
}

void main(){

	int a[5] = {5,3,4,1,2};
	MergeSort(a,0,4);
	for(int i=0;i<5;i++)
		cout<<a[i]<<" ";
	cout<<endl;
}


你可能感兴趣的:(递归合并排序)