java之并归排序

java之并归排序

直接上代码:
---------------------------------------------------------
package com.mylearn;

/**
 * 并归排序的基本排序:归并(Merge)排序法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,每个子序列是有序的。
 * 然后再把有序子序列合并为整体有序序列。
 * 
 * @author H
 *
 */
public class GuiBingFa {

	// 归并排序,首选采用分而治之的思想,运用递归方法,将数组分组两半
	public static void guibing(int[] list) {
		int L = list.length;
		// 将数组递归分成两部分
		if (L > 1) {
			// 第一部分为前一半元素
			int[] firstHalf = new int[L / 2];
			// 调用arrayCopy方法,将list中的前一半元素复制到firstHalf之中
			System.arraycopy(list, 0, firstHalf, 0, L / 2);
			// 递归:将这个子数组再分成两半
			guibing(firstHalf);
			// 第二部分为后一半元素(不一定与第一部分元素个数相同)
			int[] secondHalf = new int[L - L / 2];
			// 调用arrayCopy方法,将list中的后一半元素复制到secondHalf之中
			System.arraycopy(list, L / 2, secondHalf, 0, secondHalf.length);
			// 递归:将这个子数组再分成两半
			guibing(secondHalf);
			// 一旦所有的递归拆分都已经结束,那么进行归并
			int[] temp = merge(firstHalf, secondHalf);
			// 将temp数组的所有元素复制到list之中
			// 参数的含义:源数组,首索引,目标数组,首索引,复制长度
			System.arraycopy(temp, 0, list, 0, temp.length);
		}
	}

	// 归并两个数组
	// 因为两个数组已经是排序的,所以只需依次比较两个元素的对应值即可,"谁小就谁上"
	private static int[] merge(int[] list1, int[] list2) {
		// 声明最终数组及长度
		int[] tmp = new int[list1.length + list2.length];
		// 设置索引量初始化
		int current1 = 0, current2 = 0, current3 = 0;
		// 当两个子数组均没有结束,需要比较它们的值
		while (current1 < list1.length && current2 < list2.length) {
			if (list1[current1] < list2[current2])
				tmp[current3++] = list1[current1++];
			else
				tmp[current3++] = list2[current2++];
		}
		// 如果只剩下第一个子数组了,就直接把剩下的元素依次放入最终数组之中
		while (current1 < list1.length)
			tmp[current3++] = list1[current1++];
		// 如果只剩下第二个子数组了,就直接把剩下的元素依次放入最终数组之中
		while (current2 < list2.length)
			tmp[current3++] = list2[current2++];
		// 至此,合并结束,返回最终数组
		return tmp;
	}

	public static void main(String[] args) {
		// 首先声明数组
		int[] a = { -5, 1, 3, 2, 1, 0, 2, -2, 0 };
		int L = a.length;
		// 归并排序
		guibing(a);
		// 输出结果
		for (int element : a)
			System.out.println(element);

	}

}

------------------------------------------------------------------------------------------------------------------------------------

更多请关注:FlyTester,关注技术的测试

QQ群:456850134

web站:www.flytester.org

微信扫描二维码关注:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值