Implement Merge Sort Problem

Implement Merge Sort Problem Statement

Given a list of numbers, sort it using the Merge Sort algorithm.

Example

{
"arr": [5, 8, 3, 9, 4, 1, 7]
}

Output:

[1, 3, 4, 5, 7, 8, 9]

Notes

Constraints:

  • 1 <= length of the given list <= 105
  • -109 <= number in the list <= 109

Explanation:
https://stg.interviewkickstart.com /blogs/learn/merge-sort

Implement Merge Sort Solution 1: Iterative

Code For Implement Merge Sort Solution 1: Iterative

    /*
    Asymptotic complexity in terms of size of `arr` `n`:
    * Time: O(n * log(n)).
    * Auxiliary space: O(n).
    * Total space: O(n).
    */
    static ArrayList<Integer> merge_sort(ArrayList<Integer> arr) {
        int n = arr.size();
        int left = 0, right = n - 1;
        split(arr, left, right);
        return arr;
    }

    static void split(List<Integer> arr, int l, int h) {
        // divide the array into blocks of size [1, 2, 4, 8, ..]
        for (int blocks = 1; blocks <= h - l; blocks = 2 * blocks) {
            // for blocks = 1, i = 0, 2, 4, 6, 8 and so on
            // for each block we split the array into sub arrays and merge them
            /* note that each of these subarrays will always be sorted as we are
             building the array from smaller subarrays to larger subarrays*/
            for (int i = l; i < h; i += 2 * blocks) {
                int left = i;
                int mid = Math.min(i + blocks - 1, h);
                int right = Math.min(i + 2 * blocks - 1, h);
                merge(arr, left, mid, right);
            }
        }
    }

    /*function to merge 2 sorted arrays*/
    static void merge(List<Integer> arr, int left, int mid, int right) {
        int[] l = new int[mid - left + 1];
        //copies the integers to array l from arr
        for(int i = 0; i < mid - left + 1; i++) {
            l[i] = arr.get(left + i);
        }
        int[] r = new int[right - mid];
        //copies the integers to array r from arr
        for(int i = 0; i < right - mid; i++) {
            r[i] = arr.get(mid + i + 1);
        }
        int i = 0, j = 0, k = left;
        //merges arrays l and r back to arr
        while(i < l.length && j < r.length) {
            if(l[i] <= r[j]) {
                arr.set(k, l[i]);
                i++;
            }
            else {
                arr.set(k, r[j]);
                j++;
            }
            k++;
        }
        //merges remaining elements of arrays l and r
        while(i < l.length) {
            arr.set(k++, l[i++]);
        }
        while(j < r.length) {
            arr.set(k++, r[j++]);
        }
    }

Implement Merge Sort Solution 2: Recursive

Code For Implement Merge Sort Solution 2: Recursive

    /*
    Asymptotic complexity in terms of size of `arr` `n`:
    * Time: O(n * log(n)).
    * Auxiliary space: O(n).
    * Total space: O(n).
    */
    static ArrayList<Integer> merge_sort(ArrayList<Integer> arr) {
        int n = arr.size();
        int left = 0, right = n - 1;
        split(arr, left, right);
        return arr;
    }

    /*function to partition the array into subarrays and then merge them*/
    static void split(List<Integer> arr, int left, int right) {
        if(left < right) {
            int mid = (left + right) / 2;
            //sort first and second halves of the array
            split(arr, left, mid);
            split(arr, mid + 1, right);
            //merge the sorted halves
            merge(arr, left, mid, right);
        }
    }

    /*function to merge 2 sorted arrays*/
    static void merge(List<Integer> arr, int left, int mid, int right) {
        int[] l = new int[mid - left + 1];
        //copies the integers to array l from arr
        for(int i = 0; i < mid - left + 1; i++) {
            l[i] = arr.get(left + i);
        }
        int[] r = new int[right - mid];
        //copies the integers to array r from arr
        for(int i = 0; i < right - mid; i++) {
            r[i] = arr.get(mid + i + 1);
        }
        int i = 0, j = 0, k = left;
        //merges arrays l and r back to arr
        while(i < l.length && j < r.length) {
            if(l[i] <= r[j]) {
                arr.set(k, l[i]);
                i++;
            }
            else {
                arr.set(k, r[j]);
                j++;
            }
            k++;
        }
        //merges remaining elements of arrays l and r
        while(i < l.length) {
            arr.set(k++, l[i++]);
        }
        while(j < r.length) {
            arr.set(k++, r[j++]);
        }
    }

We hope that these solutions to merge sort problem have helped you level up your coding skills. You can expect problems like these at top tech companies like Amazon and Google.

If you are preparing for a tech interview at FAANG or any other Tier-1 tech company, register for Interview Kickstart’s FREE webinar to understand the best way to prepare.

Interview Kickstart offers interview preparation courses taught by FAANG+ tech leads and seasoned hiring managers. Our programs include a comprehensive curriculum, unmatched teaching methods, and career coaching to help you nail your next tech interview.

We offer 18 interview preparation courses, each tailored to a specific engineering domain or role, including the most in-demand and highest-paying domains and roles, such as:

‍To learn more, register for the FREE webinar.

Try yourself in the Editor

Note: Input and Output will already be taken care of.

Add Two Numbers Represented By Lists Problem

Binary Tree Level Order Traversal Problem with Examples

Jump Game

Zigzag Sort Problem

Boggle Solver Problem

Shortest String Transformation Using A Dictionary Problem

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC