用Java实现二路归并排序算法代码
归并排序(Merge Sort)是建立在归并操作上的一种有效,稳定的排序算法,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为二路归并。
运行结果:
源代码如下
public class GuiBingSort {
//排序两个有序子列,并归并为一个有序列.
static int[] sortTwoLsit(int[] array_a, int[] array_b) {
int i = 0;
int j = 0;
int a_length = array_a.length;
int b_length;
if (array_b == null) {
b_length = 0;
} else {
b_length = array_b.length;
}
int finalLength = a_length + b_length;
int[] array_c = new int[finalLength];
for (int k = 0; k < array_c.length; k++) {
if (i < a_length && j < b_length) {
if (array_a[i] < array_b[j]) {
array_c[k] = array_a[i];
i++;
} else {
array_c[k] = array_b[j];
j++;
}
} else {
if (i < a_length) {
array_c[k] = array_a[i];
i++;
}
if (j < b_length) {
array_c[k] = array_b[j];
j++;
}
}
}
return array_c;
}
//根据起始下标和子列长度取出子列
static int[] getArrayByIndex(int[] array_a, int startIndex, int newLength) {
if (startIndex + newLength > array_a.length) newLength = array_a.length - startIndex;
if (newLength <= 0) {
return null;
}
int[] newArray = new int[newLength];
for (int i = 0; i < newLength; i++) {
if (startIndex < array_a.length) {
newArray[i] = array_a[startIndex];
startIndex += 1;
}
}
return newArray;
}
//输出数组
static void outPutArray(int[] a) {
if (a != null) {
for (int d : a) {
System.out.print(d + " ");
}
} else {
System.out.print("数组为空 ");
}
}
public static void main(String[] args) {
int[] beforeSort = {3, 6, 4, 11, 7, 5, 1, 2, 9, 8, 0};
//循环1:改变子列的长度
for (int arrayLength = 1; arrayLength <= beforeSort.length; arrayLength *= 2) {
System.out.println("======================");
System.out.println("当前子列长度为:" + arrayLength);
System.out.println("======================");
//循环2:对相邻的子列进行排序
for (int i = 0; i < beforeSort.length; i += arrayLength * 2) {
System.out.print("当前步骤取出:子列a:");
outPutArray(getArrayByIndex(beforeSort, i, arrayLength));
System.out.print(",子列b:");
outPutArray(getArrayByIndex(beforeSort, i + arrayLength, arrayLength));
int[] c = sortTwoLsit(getArrayByIndex(beforeSort, i, arrayLength), getArrayByIndex(beforeSort, i + arrayLength, arrayLength));
System.out.print(",排序结果:");
outPutArray(c);
System.out.println();
//循环3:将子列排序结果返回原数组
for (int j = i, k = 0; j < i + arrayLength * 2; j++, k++) {
if (j >= beforeSort.length) break;
beforeSort[j] = c[k];
}
}
System.out.println("本长度子列整体排序结果:");
outPutArray(beforeSort);
System.out.println();
}
System.out.println("排序结束");
}
}