夜深人静写算法——合并排序(分治,非递归排序)

合并排序(非递归排序):

首先将数组a中相邻元素两两配对,用合并算法将他们排序,构成 n/2 组长度为 2 的排好序的子数组段,然后再将它们排序成长度为4的排好序的子数组段,如此继续下去,直至整个数组排好序。

程序如下:

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

template <class Type>
void Merge(Type a[],int l,int m,int r){//将数组a从l到m的部分 和从m+1到r的部分合并,重新整理到a数组中
	 Type *b = new Type [r - l];
	 int length = 0;
	 int str1 = l,str2 = m+1;
	 while(str1 <= m && str2 <= r){
	 	if(a[str1] < a[str2])
	 		b[length++] = a[str1++];
	 	else 
	 		b[length++] = a[str2++];
	 }
	while(str1 <= m)
	 	b[length++] = a[str1++];
	while(str2 <= r)
		b[length++] = a[str2++];
	
	for(int i = 0;i < length;i++)
		a[l + i] = b[i]; //复制回数组a

}

template <class Type>
void MergePass(Type a[],int s,int n){
	int i = 0;
	while(i <= n - 2*s){  //保证两两分组
		Merge(a,i ,i + s - 1, i +  2*s  - 1);
		i+=2*s;
	}
	if(i + s < n) //剩余的不足2s的时候 如果剩下的大于s时,进行合并
		Merge(a , i, i +  s - 1 ,n-1);
   //如果剩下的不足s时,默认不做处理
}

template <class Type>
void MergeSort(Type a[],int n){
	Type *b = new Type [n];   //将原数组先以两两分组,合并,然后再将大小为2的两组合并,循环下去,知道 s的大小超过了数组个数n
	int  s = 1;
	while(s < n){
		MergePass(a,s,n);
		s +=s;
	}
}
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,10);
	
	cout<<"排序后\n"; 
	for(int i = 0; i <10 ; i++){
		cout<<a[i];
		if(i!= 9)cout<<" ";
		else cout<<endl;
	}
	
}
 

猜你喜欢

转载自blog.csdn.net/curtern/article/details/83188967
今日推荐