归并排序(自用)

归并排序类似二分,并且运用了递归

#include<iostream>
using namespace std;
int a[10]={1,3,5,9,8,4,7,6,2,10};
int b[10];
void Merge(int a[],int begin,int mid,int end,int temp[]){
	int t=0,t1=begin,t2=mid+1;
	while(t1<=mid&&t2<=end){
		if(a[t1]<a[t2]){
			temp[t++]=a[t1++];
		}
		else{
			temp[t++]=a[t2++];
		}
	}
	while(t1<=mid){
		temp[t++]=a[t1++];
	}
	while(t2<=end){
		temp[t++]=a[t2++];
	}
	for(int i=0,j=begin;i<t;i++,j++){
		a[j]=temp[i];
	}	
}
void MergeSort(int a[],int begin,int end,int temp[])
{
	if(begin<end){
		int mid=(begin+end)/2;
		MergeSort(a,begin,mid,temp);
		MergeSort(a,mid+1,end,temp);
		Merge(a,begin,mid,end,temp);
	}
}
int main(){
//	int size=sizeof(a)/sizeof(int);
	MergeSort(a,0,9,b);
	for(int i=0;i<10;i++){
		cout<<a[i]<<" ";
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/henu_jizhideqingwa/article/details/80015448

相关文章