|
| 1 | +// how to implement merge sort in java? |
| 2 | + |
| 3 | +class MergeSort |
| 4 | +{ |
| 5 | + // Merges two subarrays of arr[]. |
| 6 | + // First subarray is arr[l..m] |
| 7 | + // Second subarray is arr[m+1..r] |
| 8 | + void merge(int arr[], int l, int m, int r) |
| 9 | + { |
| 10 | + // Find sizes of two subarrays to be merged |
| 11 | + int n1 = m - l + 1; |
| 12 | + int n2 = r - m; |
| 13 | + |
| 14 | + /* Create temp arrays */ |
| 15 | + int L[] = new int[n1]; |
| 16 | + int R[] = new int[n2]; |
| 17 | + |
| 18 | + /*Copy data to temp arrays*/ |
| 19 | + for (int i = 0; i < n1; ++i) |
| 20 | + L[i] = arr[l + i]; |
| 21 | + for (int j = 0; j < n2; ++j) |
| 22 | + R[j] = arr[m + 1 + j]; |
| 23 | + |
| 24 | + /* Merge the temp arrays */ |
| 25 | + |
| 26 | + // Initial indexes of first and second subarrays |
| 27 | + int i = 0, j = 0; |
| 28 | + |
| 29 | + // Initial index of merged subarray array |
| 30 | + int k = l; |
| 31 | + while (i < n1 && j < n2) { |
| 32 | + if (L[i] <= R[j]) { |
| 33 | + arr[k] = L[i]; |
| 34 | + i++; |
| 35 | + } |
| 36 | + else { |
| 37 | + arr[k] = R[j]; |
| 38 | + j++; |
| 39 | + } |
| 40 | + k++; |
| 41 | + } |
| 42 | + |
| 43 | + /* Copy remaining elements of L[] if any */ |
| 44 | + while (i < n1) { |
| 45 | + arr[k] = L[i]; |
| 46 | + i++; |
| 47 | + k++; |
| 48 | + } |
| 49 | + |
| 50 | + /* Copy remaining elements of R[] if any */ |
| 51 | + while (j < n2) { |
| 52 | + arr[k] = R[j]; |
| 53 | + j++; |
| 54 | + k++; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + // Main function that sorts arr[l..r] using |
| 59 | + // merge() |
| 60 | + void sort(int arr[], int l, int r) |
| 61 | + { |
| 62 | + if (l < r) { |
| 63 | + // Find the middle point |
| 64 | + int m =l+ (r-l)/2; |
| 65 | + |
| 66 | + // Sort first and second halves |
| 67 | + sort(arr, l, m); |
| 68 | + sort(arr, m + 1, r); |
| 69 | + |
| 70 | + // Merge the sorted halves |
| 71 | + merge(arr, l, m, r); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + /* A utility function to print array of size n */ |
| 76 | + static void printArray(int arr[]) |
| 77 | + { |
| 78 | + int n = arr.length; |
| 79 | + for (int i = 0; i < n; ++i) |
| 80 | + System.out.print(arr[i] + " "); |
| 81 | + System.out.println(); |
| 82 | + } |
| 83 | + |
| 84 | + // Driver code |
| 85 | + public static void main(String args[]) |
| 86 | + { |
| 87 | + int arr[] = { 12, 11, 13, 5, 6, 7 }; |
| 88 | + |
| 89 | + System.out.println("Given Array"); |
| 90 | + printArray(arr); |
| 91 | + |
| 92 | + MergeSort ob = new MergeSort(); |
| 93 | + ob.sort(arr, 0, arr.length - 1); |
| 94 | + |
| 95 | + System.out.println("\nSorted array"); |
| 96 | + printArray(arr); |
| 97 | + } |
| 98 | +} |
0 commit comments