Data Structures and Algorithms-归并排序(个人java实现)

public class MertSort {
	//首先我们来理清归并的思路,就假设目前我们有2个数组(A,B数组均有序)需要归并到数组(C)当中,以下为原型,
	public static  void mergTwoArray(int[] arrayA,int[] arrayB,int[] arrayC){
		int sizeA = arrayA.length;
		int sizeB = arrayB.length;
		int a = 0;//A数组指针
		int b = 0;//B数组指针
		int c = 0;//c数组指针
		
		
		while(a<sizeA&&b<sizeB){
			if(arrayA[a]>arrayB[b]){
				arrayC[c++] = arrayB[b++];
			}else{
				arrayC[c++] = arrayA[a++];
			}
		}
		//跳出这个循环代表了其中a,b数组中有1个数组的所有数组都已经用完
		while(a<sizeA){
			arrayC[c++] = arrayA[a++]; 
		}
		
		while(b<sizeB){
			arrayC[c++] =arrayB[b++];
		}
		
		for(int i=0;i<arrayC.length;i++){
			System.out.print(arrayC[i]+" ");
		}
	}
	//测试		
	public static void main(String[] args) {
		int[] arrayA = new int[]{23,36,41,55,70};
		int[] arrayB = new int[]{26,32,37,56,60};
		int[] arrayC = new int[10];
		mergTwoArray(arrayA,arrayB,arrayC);
	}
}


23 26 32 36 37 41 55 56 60 70 

以上是归并排序的部分原型


以下是归并排序的实现:

public void display(int[] array){  
	       for(int i=0;i<array.length;i++){  
	          System.out.print(array[i]+"\t");  
	       }  
	       System.out.println();  
	}  
	
	public void sort(int[] array){
		int[] workspace = new int[array.length];
		devidedSort(array,workspace,0,array.length-1);
	}
	
	//我们先用递归分解数组
	public void devidedSort(int[] array,int[] workSpace,int lowBound,int upBound){
		if(lowBound==upBound){
			return;//递归返回条件
		}else{
			int mid = (lowBound+upBound)/2;
			devidedSort(array,workSpace,lowBound,mid);
			devidedSort(array,workSpace,mid+1,upBound);
			merg(array,workSpace,lowBound,mid,upBound);
			display(array);
		}
	}

	private void merg(int[] array,int[] workspace, int lowBound,int mid, int upBound) {
		//下面2个变量定义了归并左数组的开始到结束的指针
		int lowbegin = lowBound;
		int lowend =mid;
		//下面2个变量定义了归并右数组的开始到结束的指针
		int upbegin = mid+1;
		int upend = upBound;
		//workSpace的工作指针
		int j=0;
		//归并总元素个数
		int n = upBound-lowBound+1;
		
		while(lowbegin<=lowend && upbegin<=upend){
			if(array[lowbegin] > array[upbegin]){
				workspace[j++] = array[upbegin++];
			}else{
				workspace[j++] = array[lowbegin++];
			}
		}
		
		while(lowbegin<=lowend){
			workspace[j++] = array[lowbegin++];
		}
		while(upbegin<=upend){
			workspace[j++] = array[upbegin++];
		}
		
		for(int i=0;i<j;i++){
			array[lowBound++] = workspace[i];
		}
		
	}
	
	public static void main(String[] args) {
		MertSort sort = new MertSort();
		int[] array = new int[]{6,2,7,4,8,1,5,3};
		sort.sort(array);
	}

结果如下:

2	6	7	4	8	1	5	3	
2	6	4	7	8	1	5	3	
2	4	6	7	8	1	5	3	
2	4	6	7	1	8	5	3	
2	4	6	7	1	8	3	5	
2	4	6	7	1	3	5	8	
1	2	3	4	5	6	7	8	

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值