1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| @Test public void testMergeSort() { int[] arr = {4, 2, 1, 5, 7, 6, 3}; mergeSort(arr, 0, arr.length - 1); System.out.println(Arrays.toString(arr)); }
private void mergeSort(int[] arr, int low, int high) { if (low < high) { int mid = low + (high - low) / 2; mergeSort(arr, low, mid); mergeSort(arr, mid + 1, high); merge(arr, low, mid, high); } }
private void merge(int[] arr, int low, int mid, int high) { int i = low; int j = mid + 1; int[] temp = new int[high - low + 1]; int t = 0;
while (i <= mid || j <= high) { if (i <= mid && j <= high) { if (arr[i] <= arr[j]) { temp[t++] = arr[i++]; } else { temp[t++] = arr[j++]; } } else if (i <= mid) { temp[t++] = arr[i++]; } else { temp[t++] = arr[j++]; } }
for (int e : temp) { arr[low++] = e; } }
|