import java.util.Arrays; public class My { public void mergeSort(int[] arr, int low, int high) { if (low >= high) { return; } int mid = low / 2 + high / 2; mergeSort(arr, low, mid); mergeSort(arr, mid + 1, high); merge(arr, low, mid, high); } public void merge(int[] arr, int low, int mid, int high) { int n1 = mid - low + 1; int n2 = high - mid; int[] arr1 = new int[n1]; int[] arr2 = new int[n2]; for (int i = 0; i < n1; i++) { arr1[i] = arr[low + i]; } //System.arraycopy(arr, low, arr1, 0, n1); for (int j = 0; j < n2; j++) { arr2[j] = arr[mid + 1 + j]; } //System.arraycopy(arr, mid + 1, arr2, 0, n2); int i = 0, j = 0, k = low; while (i < n1 && j < n2) { if (arr1[i] <= arr2[j]) { arr[k] = arr1[i]; k++; i++; } else { arr[k] = arr2[j]; k++; j++; } } while (i < n1) { arr[k] = arr1[i]; k++; i++; } while (j < n2) { arr[k] = arr2[j]; k++; j++; } } public static void main(String[] args) { My my = new My(); int[] arr = {5, 6, 1, 2, 4, 7, 2, 3, 4, 6, 4}; my.mergeSort(arr, 0, arr.length - 1); System.out.println(Arrays.toString(arr)); } }
原文:https://www.cnblogs.com/zzyf/p/13423711.html