DSA Tutorial



MERGE SORT


🔀 Merge Sort in DSA

Merge Sort is a Divide and Conquer algorithm. It divides the array into halves, recursively sorts them, and then merges the sorted halves.

✂️ Break the list into halves → 🧠 Sort each half → 🔧 Merge the sorted halves

🧩 How Merge Sort Works

  1. Divide the array into two halves.
  2. Recursively sort the two halves.
  3. Merge the sorted halves into a single sorted array.

📘 Step-by-Step Example

Array: [38, 27, 43, 3, 9, 82, 10]

  • Divide: [38, 27, 43] and [3, 9, 82, 10]
  • Further divide: [38] [27, 43] and [3] [9, 82, 10]
  • Sort and merge: [27, 38, 43], [3, 9, 10, 82]
  • Final merge: [3, 9, 10, 27, 38, 43, 82]

💻 C Code Example

#include <stdio.h>

void merge(int arr[], int l, int m, int r) {
    int n1 = m - l + 1;
    int n2 = r - m;
    int L[n1], R[n2];

    for (int i = 0; i < n1; i++)
        L[i] = arr[l + i];
    for (int j = 0; j < n2; j++)
        R[j] = arr[m + 1 + j];

    int i = 0, j = 0, k = l;
    while (i < n1 && j < n2) {
        if (L[i] <= R[j])
            arr[k++] = L[i++];
        else
            arr[k++] = R[j++];
    }

    while (i < n1)
        arr[k++] = L[i++];
    while (j < n2)
        arr[k++] = R[j++];
}

void mergeSort(int arr[], int l, int r) {
    if (l < r) {
        int m = l + (r - l) / 2;
        mergeSort(arr, l, m);
        mergeSort(arr, m + 1, r);
        merge(arr, l, m, r);
    }
}

int main() {
    int arr[] = {38, 27, 43, 3, 9, 82, 10};
    int n = 7;
    mergeSort(arr, 0, n - 1);
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    return 0;
}
    
📊 Time Complexity: O(n log n) in all cases
💾 Space Complexity: O(n) — Uses extra space for merging
✅ Merge Sort is stable and preferred for large datasets and linked lists where extra space is acceptable.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review