|
| 1 | +/** |
| 2 | + * Merge sort an integer arrays |
| 3 | + * |
| 4 | + * Tags: Sort |
| 5 | + */ |
| 6 | +class MergeSort { |
| 7 | + public static void main(String[] args) { |
| 8 | + MergeSort m = new MergeSort(); |
| 9 | + int[] A = { 1, 4, 2, 8, 5 }; |
| 10 | + for (int n : A) System.out.print(n + ","); |
| 11 | + System.out.println(); |
| 12 | + m.sort(A, 0, A.length - 1); |
| 13 | + for (int n : A) System.out.print(n + ","); |
| 14 | + } |
| 15 | + |
| 16 | + /** |
| 17 | + * If range exists |
| 18 | + * Get middle index |
| 19 | + * Sort first half, from low to middle |
| 20 | + * Sort second half, from middle + 1 to high |
| 21 | + * Merge these two halves |
| 22 | + */ |
| 23 | + public void sort(int[] A, int low, int high) { |
| 24 | + if (low < high) { |
| 25 | + int middle = low + (high - low) / 2; |
| 26 | + sort(A, low, middle); |
| 27 | + sort(A, middle + 1, high); |
| 28 | + merge(A, low, middle, high); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * Copy items from low to high to a helper array |
| 34 | + * Init 2 pointers |
| 35 | + * Compare value of 2 pointers, and overwrite original array, and move on |
| 36 | + * Stop when left reach middle or right reach high |
| 37 | + * Right side already in original array, so copy items remain in left side |
| 38 | + * to original array |
| 39 | + */ |
| 40 | + private void merge(int[] A, int low, int middle, int high) { |
| 41 | + int[] helper = new int[A.length]; |
| 42 | + for (int i = low; i <= high; i++) { |
| 43 | + helper[i] = A[i]; |
| 44 | + } |
| 45 | + |
| 46 | + int left = low; |
| 47 | + int right = middle + 1; |
| 48 | + int curIdx = low; |
| 49 | + |
| 50 | + while (left <= middle && right <= high) { |
| 51 | + if (helper[left] <= helper[right]) { |
| 52 | + A[curIdx] = helper[left]; |
| 53 | + left++; |
| 54 | + } else { |
| 55 | + A[curIdx] = helper[right]; |
| 56 | + right++; |
| 57 | + } |
| 58 | + curIdx++; |
| 59 | + } |
| 60 | + |
| 61 | + int remain = middle - left; // items remain in left part |
| 62 | + for (int i = 0; i <= remain; i++) { |
| 63 | + A[curIdx + i] = helper[left + i]; // move to origin array |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments