// Create temporary arrays
std::vector<int> leftArr(n1);
std::vector<int> rightArr(n2);
// Copy data to temporary arrays leftArr[] and rightArr[]
for (int i = 0; i < n1; i++) {
leftArr[i] = arr[left + i];
}
for (int i = 0; i < n2; i++) {
rightArr[i] = arr[mid + 1 + i];
}
// Merge the temporary arrays back into arr[left..right]
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (leftArr[i] <= rightArr[j]) {
arr[k++] = leftArr[i++];
} else {
arr[k++] = rightArr[j++];
}
}
// Copy the remaining elements of leftArr[], if any
while (i < n1) {
arr[k++] = leftArr[i++];
}
// Copy the remaining elements of rightArr[], if any
while (j < n2) {
arr[k++] = rightArr[j++];
}
// Recursively divide the array into two halves
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
// Merge the sorted halves
merge(arr, left, mid, right);
}
std::vector<int> arr(n);
std::cout << "Enter " << n << " elements: ";
for (int i = 0; i < n; i++) {
std::cin >> arr[i];
}
std::cout << "Original array: ";
for (int num : arr) {
std::cout << num << " ";
}
std::cout << std::endl;
mergeSort(arr, 0, arr.size() - 1);
std::cout << "Sorted array: ";
for (int num : arr) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;