#include <bits/stdc++.h>
using namespace std;
void merge(vector<int>& arr, int left,
int mid, int right)
{
int n1 = mid - left + 1;
int n2 = right - mid;
vector<int> L(n1), R(n2);
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, j = 0;
int k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(vector<int>& arr, int left, int right)
{
if (left >= right)
return;
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
void printVector(vector<int>& arr)
{
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver code
int main()
{
vector<int> arr = {8,3,7,4,2,6,5,1};
int n = arr.size();
cout << "Given vector is: \n";
printVector(arr);
mergeSort(arr, 0, n - 1);
cout << "Sorted vector is: \n";
printVector(arr);
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CnZvaWQgbWVyZ2UodmVjdG9yPGludD4mIGFyciwgaW50IGxlZnQsIAogICAgICAgICAgICAgICAgICAgICBpbnQgbWlkLCBpbnQgcmlnaHQpCnsKICAgIGludCBuMSA9IG1pZCAtIGxlZnQgKyAxOwogICAgaW50IG4yID0gcmlnaHQgLSBtaWQ7CgogICAgdmVjdG9yPGludD4gTChuMSksIFIobjIpOwoKICAgIGZvciAoaW50IGkgPSAwOyBpIDwgbjE7IGkrKykKICAgICAgICBMW2ldID0gYXJyW2xlZnQgKyBpXTsKICAgIGZvciAoaW50IGogPSAwOyBqIDwgbjI7IGorKykKICAgICAgICBSW2pdID0gYXJyW21pZCArIDEgKyBqXTsKCiAgICBpbnQgaSA9IDAsIGogPSAwOwogICAgaW50IGsgPSBsZWZ0OwoKICAgIHdoaWxlIChpIDwgbjEgJiYgaiA8IG4yKSB7CiAgICAgICAgaWYgKExbaV0gPD0gUltqXSkgewogICAgICAgICAgICBhcnJba10gPSBMW2ldOwogICAgICAgICAgICBpKys7CiAgICAgICAgfQogICAgICAgIGVsc2UgewogICAgICAgICAgICBhcnJba10gPSBSW2pdOwogICAgICAgICAgICBqKys7CiAgICAgICAgfQogICAgICAgIGsrKzsKICAgIH0KCiAgICB3aGlsZSAoaSA8IG4xKSB7CiAgICAgICAgYXJyW2tdID0gTFtpXTsKICAgICAgICBpKys7CiAgICAgICAgaysrOwogICAgfQoKICAgIHdoaWxlIChqIDwgbjIpIHsKICAgICAgICBhcnJba10gPSBSW2pdOwogICAgICAgIGorKzsKICAgICAgICBrKys7CiAgICB9Cn0KCnZvaWQgbWVyZ2VTb3J0KHZlY3RvcjxpbnQ+JiBhcnIsIGludCBsZWZ0LCBpbnQgcmlnaHQpCnsKICAgIGlmIChsZWZ0ID49IHJpZ2h0KQogICAgICAgIHJldHVybjsKCiAgICBpbnQgbWlkID0gbGVmdCArIChyaWdodCAtIGxlZnQpIC8gMjsKICAgIG1lcmdlU29ydChhcnIsIGxlZnQsIG1pZCk7CiAgICBtZXJnZVNvcnQoYXJyLCBtaWQgKyAxLCByaWdodCk7CiAgICBtZXJnZShhcnIsIGxlZnQsIG1pZCwgcmlnaHQpOwp9CgoKdm9pZCBwcmludFZlY3Rvcih2ZWN0b3I8aW50PiYgYXJyKQp7CiAgICBmb3IgKGludCBpID0gMDsgaSA8IGFyci5zaXplKCk7IGkrKykKICAgICAgICBjb3V0IDw8IGFycltpXSA8PCAiICI7CiAgICBjb3V0IDw8IGVuZGw7Cn0KCi8vIERyaXZlciBjb2RlCmludCBtYWluKCkKewogICAgdmVjdG9yPGludD4gYXJyID0gezgsMyw3LDQsMiw2LDUsMX07CiAgICBpbnQgbiA9IGFyci5zaXplKCk7CgogICAgY291dCA8PCAiR2l2ZW4gdmVjdG9yIGlzOiBcbiI7CiAgICBwcmludFZlY3RvcihhcnIpOwoKICAgIG1lcmdlU29ydChhcnIsIDAsIG4gLSAxKTsKCiAgICBjb3V0IDw8ICJTb3J0ZWQgdmVjdG9yIGlzOiBcbiI7CiAgICBwcmludFZlY3RvcihhcnIpOwogICAgcmV0dXJuIDA7Cn0=