Merge Sort

Gourab DasGourab Das
3 min read

Algorithm

  1. Divide: Split the array into two halves recursively until each subarray contains one element.

  2. Conquer: Merge the smaller sorted arrays into a single sorted array.

  3. Combine: Use the merge function to merge sorted arrays.


Pseudocode for Merge Sort

MERGE(A, low, mid, high):
    Create temporary array B
    Set i = low, j = mid+1, k = low
    WHILE i <= mid AND j <= high:
        IF A[i] < A[j]:
            B[k] = A[i]
            Increment i, k
        ELSE:
            B[k] = A[j]
            Increment j, k
    END WHILE

    Copy remaining elements from A[i] to B[k] (if any)
    Copy remaining elements from A[j] to B[k] (if any)
    Copy elements back from B to A in range [low, high]

MERGESORT(A, low, high):
    IF low < high:
        mid = (low + high) / 2
        MERGESORT(A, low, mid)
        MERGESORT(A, mid+1, high)
        MERGE(A, low, mid, high)

Example Execution

Input Array: [12, 11, 13, 5, 6, 7]

Step-by-Step Execution:

  1. Split the array into halves:

    • [12, 11, 13] and [5, 6, 7]
  2. Split further:

    • [12, 11], [13], [5, 6], [7]
  3. Split until single elements:

    • [12], [11], [13], [5], [6], [7]
  4. Merge:

    • Merge [12] and [11] -> [11, 12]

    • Merge [5] and [6] -> [5, 6]

  5. Merge sorted subarrays:

    • Merge [11, 12] and [13] -> [11, 12, 13]

    • Merge [5, 6] and [7] -> [5, 6, 7]

  6. Final Merge:

    • Merge [11, 12, 13] and [5, 6, 7] -> [5, 6, 7, 11, 12, 13]

Corrected C Code for Merge Sort

#include <stdio.h>

// Merge function
void merge(int A[], int mid, int low, int high) {
    int i, j, k, B[100];
    i = low;
    j = mid + 1;
    k = low;

    while (i <= mid && j <= high) {
        if (A[i] < A[j]) {
            B[k] = A[i];
            i++;
        } else {
            B[k] = A[j];
            j++;
        }
        k++;
    }
    while (i <= mid) {
        B[k] = A[i];
        k++;
        i++;
    }
    while (j <= high) {
        B[k] = A[j];
        k++;
        j++;
    }
    for (i = low; i <= high; i++) {
        A[i] = B[i];
    }
}

// Merge Sort function
void mergeSort(int A[], int low, int high) {
    if (low < high) {
        int mid = (low + high) / 2;
        mergeSort(A, low, mid);
        mergeSort(A, mid + 1, high);
        merge(A, mid, low, high);
    }
}

// Print the array
void printArray(int a[], int size) {
    for (int i = 0; i < size; i++)
        printf("%d ", a[i]);
    printf("\n");
}

int main() {
    int arr[] = {12, 11, 13, 5, 6, 7};
    int arrSize = sizeof(arr) / sizeof(arr[0]);

    printf("Given array:\n");
    printArray(arr, arrSize);

    mergeSort(arr, 0, arrSize - 1);

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

    return 0;
}

Example Execution

Input Array: [12, 11, 13, 5, 6, 7]
Output:
Given array:
12 11 13 5 6 7

Sorted array:
5 6 7 11 12 13


Complexity of Merge Sort

CaseTime ComplexityExplanation
Best CaseO(nlog⁡n)Recursion and merging occur, irrespective of input.
Worst CaseO(nlog⁡n)Recursion and merging occur, even for reversed arrays.
Average CaseO(nlog⁡n)Random inputs follow the same split and merge strategy.
Space ComplexityO(n)Temporary array for merging.

Important videos to understand different things

  1. for understanding concept part : https://youtu.be/3j0SWDX4AtU?si=KSdzpK6yCEQg2ES2

  2. for understanding or take visual overview of algorithm of different function :

    1. merge part : https://youtu.be/6pV2IF0fgKY?si=XjvOI2KgaMY4cwsR

    2. mergesort part : https://youtu.be/mB5HXBb_HY8?si=B3WNNN7J6O03iB08

  3. For coding part : our legend Harry bhaiya : https://youtu.be/ytK4Biw-CW4?si=iQdvsZnoH24-uWYD

Notes

  • Key Points:

    1. Merge Sort is a divide-and-conquer algorithm.

    2. It is stable (maintains the order of equal elements).

    3. Suitable for sorting large datasets as it is efficient and predictable.

20
Subscribe to my newsletter

Read articles from Gourab Das directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Gourab Das
Gourab Das