C Program for Merge Sort
Merge Sort is a comparison-based sorting algorithm that works by dividing the input array into two halves, then calling itself for these two halves, and finally it merges the two sorted halves. In this article, we will learn how to implement merge sort in C language.
What is Merge Sort Algorithm?
Merge sort is based on the three principles: divide, conquer and combine which is better implemented using recursion using two functions:
- mergeSort() - For Divide
- merge() - For Conquer and Combine
The mergeSort() function keeps dividing array into subarrays till it cannot be further divided (i.e. single element). Then merge() function is called to merge two subarrays at a time in the required order until we get back the whole array in the sorted order.
Implementation of Merge Sort in C
C language does not have inbuilt function for merge sort, so we have to manually implement it.
// C program for the implementation of merge sort
#include <stdio.h>
#include <stdlib.h>
// Merges two subarrays of arr[].
// First subarray is arr[left..mid]
// Second subarray is arr[mid+1..right]
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[left..right]
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 the remaining elements of leftArr[], if any
while (i < n1) {
arr[k] = leftArr[i];
i++;
k++;
}
// Copy the remaining elements of rightArr[], if any
while (j < n2) {
arr[k] = rightArr[j];
j++;
k++;
}
}
// The subarray to be sorted is in the index range [left-right]
void mergeSort(int arr[], int left, int right) {
if (left < right) {
// Calculate the midpoint
int mid = left + (right - left) / 2;
// 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 arr[] = { 12, 11, 13, 5, 6, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
// Sorting arr using mergesort
mergeSort(arr, 0, n - 1);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Output
Given array is 12 11 13 5 6 7 Sorted array is 5 6 7 11 12 13
Time Complexity: O(n log(n) ) in all cases.
Auxiliary Space: O(n), as all elements are copied into an auxiliary array.