Merge Sort
Merge Sort
📌 Definition:
Merge Sort is a divide and conquer sorting algorithm that divides the input array into smaller subarrays, sorts them
recursively, and then merges them back into a single sorted array.
🔍 How It Works:
1. Divide: Split the array into two halves recursively until each subarray has one element.
2. Conquer:
Sort each of the subarrays (since arrays of size 1 are trivially sorted, this is done during the merge step).
3. Combine:
Merge the sorted subarrays to produce new sorted subarrays, until the final sorted array is formed.
🔁 Example Steps (Array: [38, 27, 43, 3])
1. Divide: [38, 27] and [43, 3]
2. Divide: [38] [27] and [43] [3]
3. Merge: [27, 38] and [3, 43]
4. Merge: [3, 27, 38, 43]
⏱️ Time Complexity:
Case Time
Best O(n log n)
Average O(n log n)
Worst O(n log n)
• Each division takes log n levels.
• Each level requires O(n) time to merge the elements.
💾 Space Complexity:
• O(n) extra space is required for the temporary arrays used in merging.
✅ Advantages:
• Very predictable performance: always O(n log n)
• Stable sort (preserves the order of equal elements)
• Great for sorting linked lists (in-place version exists)
⚠️ Disadvantages:
• Uses additional memory (not in-place for arrays)
• Recursive overhead can be an issue for large arrays in memory-constrained environments
Implementation of Merge Sort in C
#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr) / sizeof(arr[0]);
printf("Given array is \n");
printArray(arr, arr_size);