| 
 | 1 | +package com.rampatra.sorting;  | 
 | 2 | + | 
 | 3 | +import java.util.Arrays;  | 
 | 4 | + | 
 | 5 | +/**  | 
 | 6 | + * @author rampatra  | 
 | 7 | + * @since 13/11/2018  | 
 | 8 | + */  | 
 | 9 | +public class MergeSortSpaceOptimized {  | 
 | 10 | + | 
 | 11 | +    /**  | 
 | 12 | +     * This is entry point. You can call this method to sort  | 
 | 13 | +     * an array {@code a}.  | 
 | 14 | +     *  | 
 | 15 | +     * @param a array to be sorted  | 
 | 16 | +     */  | 
 | 17 | +    public static void mergeSort(int[] a) {  | 
 | 18 | +        mergeSort(a, new int[a.length], 0, a.length - 1);  | 
 | 19 | +    }  | 
 | 20 | + | 
 | 21 | +    private static void mergeSort(int[] a, int[] helper, int low, int high) {  | 
 | 22 | +        if (low < high) {  | 
 | 23 | +            int mid = (low + high) / 2; // to prevent overflow you can instead do: mid = low + (high - low) / 2  | 
 | 24 | + | 
 | 25 | +            mergeSort(a, helper, low, mid);  | 
 | 26 | +            mergeSort(a, helper, mid + 1, high);  | 
 | 27 | + | 
 | 28 | +            merge(a, helper, low, mid, high);  | 
 | 29 | +        }  | 
 | 30 | +    }  | 
 | 31 | + | 
 | 32 | +    private static void merge(int[] a, int[] helper, int low, int mid, int high) {  | 
 | 33 | +        // have a helper array from which you will choose numbers and finally place it in a  | 
 | 34 | +        for (int i = low; i <= high; i++) {  | 
 | 35 | +            helper[i] = a[i];  | 
 | 36 | +        }  | 
 | 37 | + | 
 | 38 | +        int helperLeft = low;  | 
 | 39 | +        int helperRight = mid + 1;  | 
 | 40 | +        int current = low;  | 
 | 41 | + | 
 | 42 | +        // check left half of the helper array with the right half  | 
 | 43 | +        while (helperLeft <= mid && helperRight <= high) {  | 
 | 44 | +            if (helper[helperLeft] < helper[helperRight]) {  | 
 | 45 | +                a[current++] = helper[helperLeft++];  | 
 | 46 | +            } else {  | 
 | 47 | +                a[current++] = helper[helperRight++];  | 
 | 48 | +            }  | 
 | 49 | +        }  | 
 | 50 | + | 
 | 51 | +        // copy the left half of the helper array and not the right  | 
 | 52 | +        // half as the right half is already there in array a  | 
 | 53 | +        for (int i = helperLeft; i <= mid; i++) {  | 
 | 54 | +            a[current++] = helper[i];  | 
 | 55 | +        }  | 
 | 56 | +    }  | 
 | 57 | + | 
 | 58 | +    public static void main(String[] args) {  | 
 | 59 | +        int[] a = {3, 6, 8, 9, 1, 2, 4};  | 
 | 60 | +        System.out.println(Arrays.toString(a));  | 
 | 61 | +        mergeSort(a);  | 
 | 62 | +        System.out.println(Arrays.toString(a));  | 
 | 63 | +        a = new int[]{5, 8, 1, 2, 5, 3, 0, 1, 2, 4};  | 
 | 64 | +        System.out.println(Arrays.toString(a));  | 
 | 65 | +        mergeSort(a);  | 
 | 66 | +        System.out.println(Arrays.toString(a));  | 
 | 67 | +    }  | 
 | 68 | +}  | 
0 commit comments