Merge Sort

Warm Up Exercises Prior to Coding Merge Sort


Merge Sort Project

Use the following algorithm and pseudocode to help you create your own merge sort code. (The pseudocode may be more helpful than the algorithm).

General Algorithm


step 1: start

step 2: declare array and left, right, mid variable

step 3: perform merge function.
    if left > right
        return
    mid= (left+right)/2
    mergesort(array, left, mid)
    mergesort(array, mid+1, right)


Pseudocode

class MergeSort {


/* A utility function to print array of size n */

    static void printArray(int arr[])

    {

       // you write this

    }


    // Merges two subarrays of arr[].

    // First subarray is arr[l..m]

    // Second subarray is arr[m+1..r]

    void merge(int arr[], int l, int m, int r)

    {

        // Find sizes of two subarrays to be merged

         

        // Create two temp arrays of sizes calculated above

  

        // Copy data from parameter (original) array to temp arrays     

  

        // Merge the temp arrays into original array

  

        // Copy remaining elements of left subarray if any

  

        // Copy remaining elements of right subarray if any 

       

    }

  

    // Main function that sorts arr[l..r] using merge() method, above.

    void sort(int arr[], int l, int r)

    {

        if (l < r) {

            // Find the middle point

             

            // Sort first and second halves

            sort(??);  // sort the first half of the original array

            sort(??);  // sort the second half of the original array

  

            // Merge the two sorted halves of the original array into the original array 

            merge(???); 

        }

    }

  

    

  

    // Driver code

    public static void main(String args[])

    {

        int arr[] = { 12, 11, 13, 5, 6, 7 };

  

        System.out.println("Given Array");

        printArray(arr);

  

        MergeSort ob = new MergeSort();

        ob.sort(arr, 0, arr.length - 1);

  

        System.out.println("\nSorted array");

        printArray(arr);

    }

}