Merge Sort
Efficient Sorting Algorithm
Presented by:
Saurav - 23105135-016
Introduction to Merge Sort
Merge Sort is a colorful Divide and Conquer
algorithm.
It divides the input array into two halves, sorts them,
and then merges them.
Known for its efficiency, predictability, and recursion-
based logic.
Merge Sort Theory
Divide: Split the array into halves until individual
elements are left.
Conquer: Recursively sort each half.
Combine: Merge sorted halves to form the final
sorted array.
Merge Sort is Stable and Not In-Place (uses extra
memory).
Merge Sort Algorithm (Step-by-step)
1. If array size <= 1 → return.
2. Find the midpoint.
3. Recursively apply merge sort to both halves.
4. Merge the two sorted halves.
Dry Run of Merge Sort
Input: [38, 27, 43, 3, 9, 82, 10]
Step 1: Divide → [38, 27, 43] | [3, 9, 82, 10]
→ [38], [27], [43] | [3], [9], [82], [10]
Step 2: Merge → [27, 38], then [27, 38, 43]
[3, 9], then [10, 82], then [3, 9, 10, 82]
Step 3: Final Merge → [3, 9, 10, 27, 38, 43, 82]
Time Complexity Analysis
Best Case: O(n log n) - Already Sorted
Average Case: O(n log n) - Random Input
Worst Case: O(n log n) - Reverse Sorted
Why O(n log n)?
- We divide the array log n times.
- Each merge step takes O(n) time.
Space Complexity: O(n) due to temporary arrays.
Merge Sort Full Code (in C)
#include <stdio.h>
void merge(int arr[], int l, int m, int r) {
int n1 = m - l + 1, 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); } }
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) printf("%d ", arr[i]);
printf("\n"); }
int main() {
int arr[] = {38, 27, 43, 3, 9, 82, 10};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Original array: \n");
printArray(arr, size);
mergeSort(arr, 0, size - 1);
printf("\nSorted array: \n");
printArray(arr, size);
return 0; }
Example with All Cases
Best Case: [1, 2, 3, 4, 5] → O(n log n)
Average Case: [3, 5, 1, 4, 2] → O(n log n)
Worst Case: [5, 4, 3, 2, 1] → O(n log n)
Merge sort performs equally well in all cases!
Summary
Merge Sort uses Divide and Conquer.
Time Complexity is always O(n log n).
Requires additional memory (not in-place).
Very useful for large datasets.
Stable and reliable.
Welcome you all