Description: Merge sort is a classic divide-and-conquer sorting algorithm that splits an array into two halves, recursively sorts each half, and then merges the sorted halves back together. This approach ensures that the entire array is sorted in a systematic way.
Here's a C++ implementation of merge sort:
#include <iostream>
using namespace std;
void merge(int arr[], int left, int mid, int right) {
int n1 = mid - left + 1; // Size of left subarray
int n2 = right - mid; // Size of right subarray
int* L = new int[n1]; // Create left subarray
int* R = new int[n2]; // Create right subarray
// Copy data to temp arrays L[] and R[]
for (int i = 0; i < n1; i++)
L[i] = arr[left + i];
for (int j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
int i = 0; // Initial index of first subarray
int j = 0; // Initial index of second subarray
int k = left; // Initial index of merged subarray
// Merge the temp arrays back into arr[left..right]
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k++] = L[i++];
} else {
arr[k++] = R[j++];
}
}
// Copy the remaining elements of L[], if any
while (i < n1)
arr[k++] = L[i++];
// Copy the remaining elements of R[], if any
while (j < n2)
arr[k++] = R[j++];
delete[] L; // Free the temporary arrays
delete[] R;
}
void mergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2; // Prevent overflow
mergeSort(arr, left, mid); // Sort first half
mergeSort(arr, mid + 1, right); // Sort second half
merge(arr, left, mid, right); // Merge the sorted halves
}
}
int main() {
int arr[] = {38, 27, 43, 3, 9, 82, 10};
int n = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, n - 1);
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
Function Definitions:
merge: Merges two sorted subarrays into a single sorted array.mergeSort: Recursively sorts the array by dividing it into two halves.Merging Process:
merge function first calculates the sizes of the two subarrays and creates temporary arrays to hold the values.Recursive Sort:
mergeSort function recursively splits the array until it reaches base cases (single-element arrays).merge function to combine them back into a sorted array.Output: Finally, the program prints the sorted array.
Merge sort is an efficient and stable sorting algorithm, particularly suitable for large datasets. Its time complexity makes it faster than simpler algorithms like bubble sort and insertion sort for larger lists. However, its requirement for additional memory can be a downside in memory-constrained environments. Merge sort is often used in situations where stability is important, such as in external sorting scenarios where data does not fit into memory.
Open this section to load past papers