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);
}
}