|
| 1 | +/** |
| 2 | + * Java implementation of merge sort |
| 3 | + * |
| 4 | + * @author Carlos Abraham Hernandez |
| 5 | + * @email abraham@abranhe.com |
| 6 | + */ |
| 7 | + |
| 8 | +import java.util.Arrays; |
| 9 | + |
| 10 | +public class MergeSort{ |
| 11 | + |
| 12 | + // Merge the two half into a sorted data. |
| 13 | + public void merge(int arr[], int left, int middle, int right){ |
| 14 | + |
| 15 | + int n1 = middle - left + 1; |
| 16 | + int n2 = right - middle; |
| 17 | + |
| 18 | + int L[] = new int [n1]; |
| 19 | + int R[] = new int [n2]; |
| 20 | + |
| 21 | + for (int i=0; i<n1; ++i) |
| 22 | + L[i] = arr[left + i]; |
| 23 | + for (int j=0; j<n2; ++j) |
| 24 | + R[j] = arr[middle + 1+ j]; |
| 25 | + |
| 26 | + |
| 27 | + int i = 0, j = 0; |
| 28 | + |
| 29 | + int k = left; |
| 30 | + while (i < n1 && j < n2){ |
| 31 | + if (L[i] <= R[j]){ |
| 32 | + arr[k] = L[i]; |
| 33 | + i++; |
| 34 | + } |
| 35 | + else{ |
| 36 | + arr[k] = R[j]; |
| 37 | + j++; |
| 38 | + } |
| 39 | + k++; |
| 40 | + } |
| 41 | + |
| 42 | + while (i < n1){ |
| 43 | + arr[k] = L[i]; |
| 44 | + i++; |
| 45 | + k++; |
| 46 | + } |
| 47 | + |
| 48 | + /* Copy remaining elements of R[] if any */ |
| 49 | + while (j < n2){ |
| 50 | + arr[k] = R[j]; |
| 51 | + j++; |
| 52 | + k++; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + // Main function that sorts arr[l..r] using |
| 57 | + void sort(int arr[], int left, int right){ |
| 58 | + if (left < right){ |
| 59 | + // Find the middle point |
| 60 | + int middle = (left+right)/2; |
| 61 | + |
| 62 | + // Sort first and second halves |
| 63 | + sort(arr, left, middle); |
| 64 | + sort(arr , middle+1, right); |
| 65 | + |
| 66 | + // Merge the sorted halves |
| 67 | + merge(arr, left, middle, right); |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + //Default values |
| 72 | + void sort(int arr[]){ |
| 73 | + int l = 0; // First index |
| 74 | + int r = arr.length-1; // Last index |
| 75 | + sort(arr, l, r); |
| 76 | + } |
| 77 | + |
| 78 | + // Test Functionality |
| 79 | + public static void main(String args[]){ |
| 80 | + |
| 81 | + int[] arr = new int[20]; |
| 82 | + |
| 83 | + for(int i = 0; i < arr.length; i++) { |
| 84 | + arr[i] = (int)(Math.random()*999 + 1); |
| 85 | + } |
| 86 | + |
| 87 | + System.out.println("Unordered List: \n" + Arrays.toString(arr)); |
| 88 | + |
| 89 | + MergeSort m = new MergeSort(); |
| 90 | + m.sort(arr); |
| 91 | + |
| 92 | + System.out.println("Ordered List: \n" + Arrays.toString(arr)); |
| 93 | + } |
| 94 | +} |
0 commit comments