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
| private int[] mergeSort(int[] arr) { int[] tmp = new int[arr.length]; mergeSort(arr, 0, arr.length - 1, tmp);
return arr; }
private void mergeSort(int[] arr, int start, int end, int[] tmp) { if (start == end) return; int middle = (end - start) / 2 + start;
mergeSort(arr, start, middle, tmp); mergeSort(arr, middle + 1, end, tmp);
merge(arr, start, end, tmp); }
private void merge(int[] arr, int start, int end, int[] tmp) { int middle = (end - start) / 2 + start;
int start1 = start; int end1 = middle;
int start2 = middle + 1; int end2 = end;
for (int i = start1; i <= end2; i++) { if (start1 > end1) { tmp[i] = arr[start2++]; } else if (start2 > end2) { tmp[i] = arr[start1++]; } else if (arr[start1] > arr[start2]) { tmp[i] = arr[start2++]; } else { tmp[i] = arr[start1++]; } }
for (int i = start; i <= end; i++) { arr[i] = tmp[i]; } }
|