代码如下:
import java.util.Arrays; public class MergeSort { public static void main(String[] args) { int[] intArr = SortBase.generateIntArr(1, 100, 20); System.out.println(Arrays.toString(intArr)); // 使用java自带排序算法,用于结果比对 int[] tmp = new int[intArr.length]; System.arraycopy(intArr, 0, tmp, 0, intArr.length); Arrays.sort(tmp); System.out.println(Arrays.toString(tmp)); solution(intArr, tmp, 0, intArr.length - 1); System.out.println(Arrays.toString(intArr)); } public static void solution(int[] arr, int[] tmp, int start, int end) { if (start >= end) { return; } int mid = start + ((end - start) >> 1); int start1 = start; int end1 = mid; int start2 = mid + 1; int end2 = end; // System.out.println(start1+"_"+end1+"_"+start2+"_"+end2); solution(arr, tmp, start1, end1); solution(arr, tmp, start2, end2); int k = start; while (start1 <= end1 && start2 <= end2) { tmp[k++] = arr[start1] <= arr[start2] ? arr[start1++] : arr[start2++]; } while (start1 <= end1) { tmp[k++] = arr[start1++]; } while (start2 <= end2) { tmp[k++] = arr[start2++]; } for (k = start; k <= end; k++) { arr[k] = tmp[k]; } } }