- What is merge sort and how it works
- How to implement merge sort in C using recursion
- How merge sort uses divide-and-conquer strategy
- Step-by-step explanation of the program
- Time and space complexity of merge sort
- Practice exercises to test your understanding
Introduction
In this tutorial, we will learn how to write a C program to sort an array using the merge sort algorithm.
Merge sort is a highly efficient, comparison-based sorting algorithm that follows the divide-and-conquer paradigm. It works by dividing the array into two halves, recursively sorting each half, and then merging the sorted halves back together.
💡 Key Point: Merge sort is one of the most efficient sorting algorithms with a guaranteed time complexity of O(n log n) in all cases. It is widely used in practice for sorting large datasets.
Merge sort is used in various real-world applications, such as:
- Large Datasets: Efficiently sorts large arrays with predictable performance
- External Sorting: Used in external sorting algorithms for large files
- Stable Sorting: Maintains relative order of equal elements
- Parallel Processing: Can be easily parallelized for multi-core systems
Visual Example
Let's see how merge sort sorts the array [38, 27, 43, 3, 9, 82, 10]:
Step 1: Divide the array
[38, 27, 43, 3, 9, 82, 10] [38, 27, 43] [3, 9, 82, 10] [38] [27, 43] [3, 9] [82, 10] [38] [27] [43] [3] [9] [82] [10]
Step 2: Merge the subarrays
[38] [27] [43] [3] [9] [82] [10] [27, 38] [43] [3, 9] [10, 82] [27, 38, 43] [3, 9, 10, 82] [3, 9, 10, 27, 38, 43, 82]
Final Sorted Array: [3, 9, 10, 27, 38, 43, 82]
C Program for Merge Sort
#include <stdio.h>
// Function to merge two subarrays
void merge(int arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
// Create temporary arrays
int leftArr[n1], rightArr[n2];
// Copy data to temporary arrays
for(i = 0; i < n1; i++)
leftArr[i] = arr[left + i];
for(j = 0; j < n2; j++)
rightArr[j] = arr[mid + 1 + j];
// Merge the temporary arrays back into arr[]
i = 0;
j = 0;
k = left;
while(i < n1 && j < n2) {
if(leftArr[i] <= rightArr[j]) {
arr[k] = leftArr[i];
i++;
} else {
arr[k] = rightArr[j];
j++;
}
k++;
}
// Copy remaining elements of leftArr[]
while(i < n1) {
arr[k] = leftArr[i];
i++;
k++;
}
// Copy remaining elements of rightArr[]
while(j < n2) {
arr[k] = rightArr[j];
j++;
k++;
}
}
// Function to perform merge sort
void mergeSort(int arr[], int left, int right) {
if(left < right) {
int mid = left + (right - left) / 2;
// Recursively sort first and second halves
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
// Merge the sorted halves
merge(arr, left, mid, right);
}
}
int main() {
int n, i;
// Ask user for number of elements
printf("Enter the number of elements: ");
scanf("%d", &n);
// Declare array
int arr[n];
// Read elements into the array
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Perform merge sort
mergeSort(arr, 0, n - 1);
// Display sorted array
printf("\nSorted array in ascending order: ");
for(i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Sample Output
Enter the number of elements: 7 Enter 7 elements: 38 27 43 3 9 82 10 Sorted array in ascending order: 3 9 10 27 38 43 82
Another Example:
Enter the number of elements: 6 Enter 6 elements: 12 11 13 5 6 7 Sorted array in ascending order: 5 6 7 11 12 13
Example with Negative Numbers:
Enter the number of elements: 6 Enter 6 elements: -5 10 -2 8 0 -10 Sorted array in ascending order: -10 -5 -2 0 8 10
Program Explanation
Let's break down the code step by step:
- Include Header File:
#include <stdio.h>includes the standard input/output library. - merge() Function:
- Merges two sorted subarrays:
arr[left...mid]andarr[mid+1...right] - Creates temporary arrays
leftArrandrightArr - Compares elements and merges them in sorted order
- Merges two sorted subarrays:
- mergeSort() Function:
- Recursively divides the array into two halves
- Calls itself on the left and right halves
- Merges the sorted halves using the
merge()function
- main() Function:
- Gets user input for the array
- Calls
mergeSort(arr, 0, n-1)to sort the array - Prints the sorted array
📝 Note: Merge sort has a guaranteed time complexity of O(n log n) in all cases, making it one of the most efficient sorting algorithms.
Merge Sort Algorithm
Step-by-step algorithm:
- Start
- Read the array elements
- If
left < right:- Find the middle index:
mid = left + (right - left) / 2 - Recursively sort the left half:
mergeSort(arr, left, mid) - Recursively sort the right half:
mergeSort(arr, mid + 1, right) - Merge the two sorted halves:
merge(arr, left, mid, right)
- Find the middle index:
- Print the sorted array
- End
Time and Space Complexity
| Scenario | Time Complexity | Space Complexity |
|---|---|---|
| Best Case | O(n log n) | O(n) |
| Worst Case | O(n log n) | O(n) |
| Average Case | O(n log n) | O(n) |
💡 Note: Merge sort requires O(n) extra space for the temporary arrays used during merging. It is a stable sorting algorithm.
💻 Practice Exercise
Challenge 1: Modify the merge sort program to sort the array in descending order.
Challenge 2: Implement merge sort iteratively (without recursion).
🔍 Click to Show Solution for Challenge 1
// Change the comparison in the merge function
if(leftArr[i] >= rightArr[j]) { // Change <= to >= for descending
arr[k] = leftArr[i];
i++;
} else {
arr[k] = rightArr[j];
j++;
}
Frequently Asked Questions
1. What is merge sort in C?
Merge sort is a divide-and-conquer sorting algorithm that divides the array into two halves, recursively sorts them, and then merges the sorted halves.
2. What is the time complexity of merge sort?
Merge sort has a time complexity of O(n log n) in all cases (best, average, worst).
3. Is merge sort stable?
Yes, merge sort is a stable sorting algorithm. It maintains the relative order of equal elements.
4. What is the space complexity of merge sort?
Merge sort has a space complexity of O(n) due to the temporary arrays used during merging.
5. When should I use merge sort?
Merge sort is ideal for large datasets, linked lists, and when stable sorting is required. It's also good for external sorting where data doesn't fit in memory.
💡 Tip: Merge sort is one of the most important sorting algorithms to learn. Its divide-and-conquer approach is used in many other algorithms like Quick Sort and Binary Search.