Find a permutation that causes worst case of Merge Sort

3.4

Given a set of elements, find which permutation of these elements would result in worst case of Merge Sort?

Asymptotically, merge sort always takes ?(n Log n) time, but the cases that require more comparisons generally take more time in practice. We basically need to find a permutation of input elements that would lead to maximum number of comparisons when sorted using a typical Merge Sort algorithm.

Example:

Consider the below set of elements 
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 
 13, 14, 15, 16}

Below permutation of the set causes 153
comparisons.
{1, 9, 5, 13, 3, 11, 7, 15, 2, 10, 6, 
 14, 4, 12, 8, 16}

And an already sorted permutation causes
30 comparisons. 

See this for a program that counts 
comparisons and shows above results.

Now how to get worst case input for merge sort for an input set?

Lets us try to build the array in bottom up manner

Let the sorted array be {1,2,3,4,5,6,7,8}.

In order to generate the worst case of merge sort, the merge operation that resulted in above sorted array should result in maximum comparisons. In order to do so, the left and right sub-array involved in merge operation should store alternate elements of sorted array. i.e. left sub-array should be {1,3,5,7} and right sub-array should be {2,4,6,8}. Now every element of array will be compared at-least once and that will result in maximum comparisons. We apply the same logic for left and right sub-array as well. For array {1,3,5,7}, the worst case will be when its left and right sub-array are {1,5} and {3,7} respectively and for array {2,4,6,8} the worst case will occur for {2,4} and {6,8}.

Complete Algorithm –

GenerateWorstCase(arr[])

  1. 1. Create two auxillary arrays left and right and store alternate array elements in them.
  2. Call GenerateWorstCase for left subarray: GenerateWorstCase (left)
  3. Call GenerateWorstCase for right subarray: GenerateWorstCase (right)
  4. Copy all elements of left and right subarrays back to original array.

Below is implementation of the idea

C/C++

// C/C++ program to generate Worst Case of Merge Sort
#include <stdlib.h>
#include <stdio.h>

// Function to print an array
void printArray(int A[], int size)
{
    for (int i = 0; i < size; i++)
        printf("%d ", A[i]);

    printf("\n");
}

// Function to join left and right subarray
int join(int arr[], int left[], int right[],
          int l, int m, int r)
{
    int i; // Used in second loop
    for (i = 0; i <= m - l; i++)
        arr[i] = left[i];

    for (int j = 0; j < r - m; j++)
        arr[i + j] = right[j];
}

// Function to store alternate elemets in left
// and right subarray
int split(int arr[], int left[], int right[],
          int l, int m, int r)
{
    for (int i = 0; i <= m - l; i++)
        left[i] = arr[i * 2];

    for (int i = 0; i < r - m; i++)
        right[i] = arr[i * 2 + 1];
}

// Function to generate Worst Case of Merge Sort
int generateWorstCase(int arr[], int l, int r)
{
    if (l < r)
    {
        int m = l + (r - l) / 2;

        // create two auxillary arrays
        int left[m - l + 1];
        int right[r - m];

        // Store alternate array elements in left
        // and right subarray
        split(arr, left, right, l, m, r);

        // Recurse first and second halves
        generateWorstCase(left, l, m);
        generateWorstCase(right, m + 1, r);

        // join left and right subarray
        join(arr, left, right, l, m, r);
    }
}

// Driver code
int main()
{
    // Sorted array
    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9,
                 10, 11, 12, 13, 14, 15, 16 };
    int n = sizeof(arr) / sizeof(arr[0]);

    printf("Sorted array is \n");
    printArray(arr, n);

    // generate Worst Case of Merge Sort
    generateWorstCase(arr, 0, n - 1);

    printf("\nInput array that will result in "
             "worst case of merge sort is \n");
    printArray(arr, n);

    return 0;
}

Java

// Java program to generate Worst Case of Merge Sort

import java.util.Arrays;

class GFG 
{
    // Function to join left and right subarray
    static void join(int arr[], int left[], int right[],
                    int l, int m, int r)
    {
        int i;
        for (i = 0; i <= m - l; i++)
            arr[i] = left[i];
 
        for (int j = 0; j < r - m; j++)
            arr[i + j] = right[j];
    }
 
    // Function to store alternate elemets in left
    // and right subarray
    static void split(int arr[], int left[], int right[],
                     int l, int m, int r)
    {
        for (int i = 0; i <= m - l; i++)
            left[i] = arr[i * 2];
 
        for (int i = 0; i < r - m; i++)
            right[i] = arr[i * 2 + 1];
    }
    
    // Function to generate Worst Case of Merge Sort
    static void generateWorstCase(int arr[], int l, int r)
    {
        if (l < r)
        {
            int m = l + (r - l) / 2;
 
            // create two auxillary arrays
            int[] left = new int[m - l + 1];
            int[] right = new int[r - m];
 
            // Store alternate array elements in left
            // and right subarray
            split(arr, left, right, l, m, r);
 
            // Recurse first and second halves
            generateWorstCase(left, l, m);
            generateWorstCase(right, m + 1, r);
 
            // join left and right subarray
            join(arr, left, right, l, m, r);
        }
    }
    
    // driver program
	public static void main (String[] args) 
	{
	    // sorted array
		int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9,
                      10, 11, 12, 13, 14, 15, 16 };
        int n = arr.length;
        System.out.println("Sorted array is");
        System.out.println(Arrays.toString(arr));
        
        // generate Worst Case of Merge Sort
        generateWorstCase(arr, 0, n - 1);
 
        System.out.println("\nInput array that will result in \n"+
             "worst case of merge sort is \n");
    
        System.out.println(Arrays.toString(arr));
	}
}

// Contributed by Pramod Kumar


Output:
Sorted array is 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 

Input array that will result in worst 
case of merge sort is 
1 9 5 13 3 11 7 15 2 10 6 14 4 12 8 16 

References – Stack Overflow

This article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



3.4 Average Difficulty : 3.4/5.0
Based on 9 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.