归并排序
原数组:5, 7, 8, 3, 1, 2, 4, 6
5,7,8,3 | 1,2,4,6(第一步将数组一分为二,即为左右两边)
5,7 | 8,3 | 1,2 | 4,6(第二步左右两边都循环一分为二直到只有一个元素停止,之后进行排序)
5,7 | 3,8(即左边的两边排序好) 1,2 | 4,6(即右边的两边排序好)
3,5,7,8(即左边都排序好) 1,2,4,6(即右边都排序好)
1,2,3,4,5,6,7,8(全部排序好)
import cn.hutool.core.util.ArrayUtil;
import java.util.Arrays;
public class MergeSortTest {
public static void main(String[] args) {
int[] arr = {5, 7, 8, 3, 1, 2, 4, 6};
if (ArrayUtil.isEmpty(arr) || arr.length < 2) {
System.out.println(Arrays.toString(arr));
}
int[] temp = new int[arr.length];
mergeSort(arr, temp, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
public static void mergeSort(int[] arr, int[] temp, int left, int right) {
if (left < right) {
// 取中间点索引,为了防止left不为0的情况,不使用(left+right)/2,
int center = left + (right - left) / 2;
mergeSort(arr, temp, left, center);
mergeSort(arr, temp, center + 1, right);
merge(arr, temp, left, center, right);
}
}
public static void merge(int[] arr, int[] temp, int left, int center, int right) {
int i = left;
int j = center + 1;
for (int k = left; k <= right; k++) {
if (i > center) {
temp[k] = arr[j++];
} else if (j > right) {
temp[k] = arr[i++];
} else if (arr[j] > arr[i]) {
temp[k] = arr[i++];
} else {
temp[k] = arr[j++];
}
}
for (int k = left; k <= right; k++) {
arr[k] = temp[k];
}
}
}