Merge Sort is a highly efficient, stable, and comparison-based sorting algorithm. Its implementation in the C programming language showcases its divide-and-conquer strategy. This article delves into the fundamental principles of Merge Sort and provides a detailed walkthrough of its implementation in C.
Understanding Merge Sort
Conceptual Overview
Merge Sort divides an array into two halves, sorts each half, and then merges the sorted halves. This recursive approach ensures a time complexity of O(n log n), making it highly efficient for large datasets.
Algorithmic Steps
- Divide: Split the array into two halves.
- Conquer: Recursively sort each half.
- Merge: Combine the sorted halves into a single sorted array.
Implementing Merge Sort in C
Setting Up the Environment
Before diving into the code, ensure your C programming environment is set up. Any standard C compiler like GCC will suffice.
Code Walkthrough
#include <stdio.h>
void merge(int array[], int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
// Temporary arrays
int L[n1], R[n2];
// Copy data to temp arrays L[] and R[]
for (int i = 0; i < n1; i++)
L[i] = array[left + i];
for (int j = 0; j < n2; j++)
R[j] = array[mid + 1 + j];
// Merge the temp arrays back into array[left..right]
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
array[k] = L[i];
i++;
} else {
array[k] = R[j];
j++;
}
k++;
}
// Copy remaining elements of L[], if any
while (i < n1) {
array[k] = L[i];
i++;
k++;
}
// Copy remaining elements of R[], if any
while (j < n2) {
array[k] = R[j];
j++;
k++;
}
}
void mergeSort(int array[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
// Sort first and second halves
mergeSort(array, left, mid);
mergeSort(array, mid + 1, right);
merge(array, left, mid, right);
}
}
// Function to print an array
void printArray(int A[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
// Driver code
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);
mergeSort(arr, 0, arr_size - 1);
printf("\nSorted array is \n");
printArray(arr, arr_size);
return 0;
}
Explanation of the Code
- Function
merge
: This function takes a sub-array and two indices. It merges the two sorted halves. - Function
mergeSort
: This recursive function divides the array and callsmerge
on the divided parts. - Utility Functions:
printArray
to display the sorted array.
Conclusion
Merge Sort in C demonstrates the algorithm’s robustness and efficiency. Its divide-and-conquer methodology makes it a preferred choice for sorting large datasets. The provided code offers a clear understanding of how Merge Sort operates and can be utilized in various applications requiring sorted data