归并排序思想及模板(简洁版)

博客介绍了归并排序思路,以两个有序数组[2]和[1]为例,说明可将其按顺序合并为[1,2]。对于要排序的数组,可将其分为两部分,通过递归实现上述合并过程,使用Java语言实现。

归并排序思路

  1. 对于任意两个有序数组 例如:[2]和[1]
  2. 可以按顺序把这两个数组合并为一个数组 ([1,2])
  3. 把要排序的数组分为两个部分,递归地对数组实现上述过程
public class MergeArray {
	//总调用接口
	private static void mergeSort(int[] a, int n) {
		int[] temp = new int[n];
		mSort(a,temp,0,n-1);
	}
	
	//递归体
	private static void mSort(int[] a, int[] temp, int l, int r) {
		int mid = (l+r)/2;
		if(l<r) {
			mSort(a,temp,l,mid);
			mSort(a,temp,mid+1,r);
			merge(a, temp, l, mid+1, r);
		}
	}
	
	//合并
	private static void merge(int[] a, int[] tempA, int l, int r, int rightEnd) {
		int leftEnd = r-1;
		int tempIndex = l;
		int length = rightEnd-l+1;
		while(l<=leftEnd&&r<=rightEnd) {
			if(a[l]<=a[r]) {
				tempA[tempIndex++] = a[l++];
			}else {
				tempA[tempIndex++] = a[r++];
			}
		}
		while(l<=leftEnd) {
			tempA[tempIndex++] = a[l++];
		}
		while(r<=rightEnd) {
			tempA[tempIndex++] = a[r++];
		}
		for(int i = 0;i<length;i++,rightEnd--) {
			a[rightEnd] = tempA[rightEnd];
		}
	}
	
	public static void main(String[] args) {
		int a[] = new int[] {1,2,6,2,4,4,2,0,1,8,7};
		int temp[] = new int[a.length];
		mergeSort(a,a.length);
		System.out.println(Arrays.toString(a));
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值