无聊中写的归并排序算法。
package my.sort;
public class MergeSort {
public static void main(String[] args) {
int[] array = {9, 1, 5, 3, 4, 2, 6, 7, 10, 8, 3, 13, 44, 13, 17, 77, 44, 55, 23, 48, 112, 44, 55, 66, 222, 43, 56, 32, 34, 45, 324, 25, 45, 23, 69,100,87,83,29};
mergeSort(array);
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
};
public static void mergeSort(int[] arr) {
for (int space = 1; space < arr.length; space *= 2) {// space数字间隔,即每次进行归并的字数组的长度
for (int leftStart = 0; leftStart <= arr.length - 1; leftStart += space * 2) {
int rightStart = leftStart + space;
if(rightStart <= arr.length - 1){
merge(arr, leftStart, rightStart, space);
}
}
}
}
public static void merge(int[] arr, int leftStart, int rightStart, int space) {
int leftEnd = leftStart + space - 1;// 左边有序数组的止点下标
int rightEnd = rightStart + space - 1 > arr.length - 1 ? arr.length - 1 : rightStart + space - 1;
int[] tempArr = new int[rightEnd - leftStart + 1];// 存放临时有序数组
// 一下是有序数据合并的代码
int i = leftStart;
int j = rightStart;
int k = 0;
while (i <= leftEnd && j <= rightEnd) {
if (arr[i] < arr[j]) {
tempArr[k] = arr[i];
i++;
} else {
tempArr[k] = arr[j];
j++;
}
k++;
}
while (i <= leftEnd) {
tempArr[k] = arr[i];
i++;
k++;
}
while (j <= rightEnd) {
tempArr[k] = arr[j];
j++;
k++;
}
for (int n = 0, m = leftStart; m <= rightEnd; m++, n++) {
arr[m] = tempArr[n];
}
}
}