C in 100 Seconds: Merge Sort
Video: C in 100 Seconds: Merge Sort | Episode 54 by CelesteAI
Watch full page →Merge Sort — Divide and Conquer
Split the array in half, sort each half recursively, then merge them back together. O(n log n) — much faster than bubble sort on large arrays.
How It Works
The merge_sort function finds the midpoint, recursively sorts the left and right halves, then calls merge to combine them. Base case: a single element is already sorted.
The Merge
void merge(int arr[], int left, int mid, int right) {
int i = left, j = mid + 1, k = 0;
int temp[right - left + 1];
while (i <= mid && j <= right) {
if (arr[i] <= arr[j]) temp[k++] = arr[i++];
else temp[k++] = arr[j++];
}
while (i <= mid) temp[k++] = arr[i++];
while (j <= right) temp[k++] = arr[j++];
for (int i = 0; i < k; i++) arr[left + i] = temp[i];
}
Two pointers walk through the sorted halves. The smaller element goes into temp each time. When one side runs out, copy the rest.
The Recursive Split
void merge_sort(int arr[], int left, int right) {
if (left >= right) return;
int mid = (left + right) / 2;
merge_sort(arr, left, mid);
merge_sort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
Output
Before: 38 27 43 3 9 82 10
After: 3 9 10 27 38 43 82
Student code: GitHub