归并排序

时间复杂度:

O(n log n

算法稳定性:

稳定

原理:

将两个有序数组归并为一个有序数组。(元素数量为 1 时也是有序数组哦)

步骤:

整个排序过程中有一个原数组 S ,有一个临时数组 T。分为两个步骤分割和归并。

1:将数组递归的从中间分割为两个子序列,直到不可在分(即子序列元素数量小于 1 )。然后利用 T 对两个子序列进行归并, 在将 T 中数据复制到 S。

2:退出递归得到结果。

没有图!

注:本系列算法是用于记录自己学习算法阶段对每个算法的自己理解。

@Override
	public int[] sort(int[] source) {
		int[] temp = new int[source.length];
		return limit(source, temp, 0, source.length - 1);
	}
	
	public int[] limit(int[] source, int[] temp, int l, int r){
		if (r - l < 1){
			return source;
		}
		limit(source, temp, l, (l + r)/2);
		limit(source, temp, (l + r)/2 + 1, r);
		return merge(source, temp, l,  (l + r)/2, r);
	}
	
	public int[] merge(int[] source,int[] temp, int l, int le, int r){
		int rs = le + 1;
		int index = l;
		int start = l;
		while (l <= le && rs <= r){
			if (source[l] < source[rs]){
				temp[index++] = source[l++];
			} else {
				temp[index++] = source[rs++];
			}
		}
		while (l <= le){
			temp[index++] = source[l++];
		}
		while (rs <= r){
			temp[index++] = source[rs++];
		}
		return arrCopy(source, start, r, temp);
	}

	public static int[] arrCopy(int[] source, int l, int r, int[] temp){
		for (int j = l; j <= r; j++){
			source[j] = temp[j];
		}
		return source;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值