夜深人靜寫算法——合併排序(分治,遞歸)

 

合併排序:
採用分治的方法。

第一步:

(1) 將數組分成兩部分

(2)然後將分開的數組當成一個新的數組 ,重複操作(1),直到數組的大小爲1.

第二步:
將分開的已排好的小數組進行合併(按照一定的順序)。

因爲最小的數組的大小爲1,然後進行合併的排序,所以可以保證小數組總是排好序的

#include <stdio.h>
#include <iostream>
#include <algorithm>
#define MAX 100
using namespace std;

template <class Type>
void Merge(Type a[MAX],int left1,int right1,int left2,int right2)//合併兩個數組 
{         //將數組a的第left1到第right1 和 數組a的第left2到right2 進行合併

	int str1 = left1,str2 = left2; 
	int length  = 0 ;
	Type b[MAX];
	
	while(str1 <= right1 && str2 <= right2){
		if(a[str1] < a[str2]){
			b[length++] = a[str1++];
		 
		}else
			b[length++] = a[str2++];	 
	}
	
	if(str1 <= right1)
		for(int i = str1; i <= right1 ; i++)
			b[length++] = a[i];
	else if( str2 <= right2)
		for(int i = str2; i <= right2; i++)
			b[length++] = a[i];
	
 
	for(int i = left1 ; i < left1 + length; i++ ) //將合併好的數組b複製到a的原始位置(left1到right2)
		a[i] = b[i - left1] ;
	
	
} 

template <class Type>
void Mergesort(Type a[MAX],int left,int right){
	if(left < right){  //數組的大小至少爲2
		int j= (left + right)/2; //將數組分爲兩部分,
		Mergesort(a,left,j); 
		Mergesort(a,j+1,right);
		Merge(a,left,j,j+1,right); //合併
	}
}
int main(){
	int a[10] = { 2,1,5,4,3,7,6,8,9,0};
	
	for(int i = 0; i <10 ; i++){
		cout<<a[i];
		if(i!= 9)cout<<" ";
		else cout<<endl;
	}
	
	Mergesort(a,0,9);
	
	cout<<"排序後\n"; 
	for(int i = 0; i <10 ; i++){
		cout<<a[i];
		if(i!= 9)cout<<" ";
		else cout<<endl;
	}
	
	return 0;	
	
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章