#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;
}
int main()
{
vector<int> arr = { 12, 11, 13, 5, 6, 7 };
int n = arr.size();
cout << "Given vector is \n";
printVector(arr);
clock_t begin = clock();
mergeSort(arr, 0, n - 1);
cout << "\nSorted vector is \n";
printVector(arr);
clock_t end = clock();
cout<<"Time run: "<<fixed << (float)(end-begin)/CLOCKS_PER_SEC<<" s"<<endl;
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7Cgp2b2lkIG1lcmdlKHZlY3RvcjxpbnQ+JiBhcnIsIGludCBsZWZ0LCAKICAgICAgICAgICAgICAgICAgICAgaW50IG1pZCwgaW50IHJpZ2h0KQp7CiAgICBpbnQgbjEgPSBtaWQgLSBsZWZ0ICsgMTsKICAgIGludCBuMiA9IHJpZ2h0IC0gbWlkOwogICAgdmVjdG9yPGludD4gTChuMSksIFIobjIpOwogICAgZm9yIChpbnQgaSA9IDA7IGkgPCBuMTsgaSsrKQogICAgICAgIExbaV0gPSBhcnJbbGVmdCArIGldOwogICAgZm9yIChpbnQgaiA9IDA7IGogPCBuMjsgaisrKQogICAgICAgIFJbal0gPSBhcnJbbWlkICsgMSArIGpdOwogICAgaW50IGkgPSAwLCBqID0gMDsKICAgIGludCBrID0gbGVmdDsKICAgIHdoaWxlIChpIDwgbjEgJiYgaiA8IG4yKSB7CiAgICAgICAgaWYgKExbaV0gPD0gUltqXSkgewogICAgICAgICAgICBhcnJba10gPSBMW2ldOwogICAgICAgICAgICBpKys7CiAgICAgICAgfQogICAgICAgIGVsc2UgewogICAgICAgICAgICBhcnJba10gPSBSW2pdOwogICAgICAgICAgICBqKys7CiAgICAgICAgfQogICAgICAgIGsrKzsKICAgIH0KICAgIHdoaWxlIChpIDwgbjEpIHsKICAgICAgICBhcnJba10gPSBMW2ldOwogICAgICAgIGkrKzsKICAgICAgICBrKys7CiAgICB9CiAgICB3aGlsZSAoaiA8IG4yKSB7CiAgICAgICAgYXJyW2tdID0gUltqXTsKICAgICAgICBqKys7CiAgICAgICAgaysrOwogICAgfQp9CnZvaWQgbWVyZ2VTb3J0KHZlY3RvcjxpbnQ+JiBhcnIsIGludCBsZWZ0LCBpbnQgcmlnaHQpCnsKICAgIGlmIChsZWZ0ID49IHJpZ2h0KQogICAgICAgIHJldHVybjsKCiAgICBpbnQgbWlkID0gbGVmdCArIChyaWdodCAtIGxlZnQpIC8gMjsKICAgIG1lcmdlU29ydChhcnIsIGxlZnQsIG1pZCk7CiAgICBtZXJnZVNvcnQoYXJyLCBtaWQgKyAxLCByaWdodCk7CiAgICBtZXJnZShhcnIsIGxlZnQsIG1pZCwgcmlnaHQpOwp9Cgp2b2lkIHByaW50VmVjdG9yKHZlY3RvcjxpbnQ+JiBhcnIpCnsKICAgIGZvciAoaW50IGkgPSAwOyBpIDwgYXJyLnNpemUoKTsgaSsrKQogICAgICAgIGNvdXQgPDwgYXJyW2ldIDw8ICIgIjsKICAgIGNvdXQgPDwgZW5kbDsKfQoKCmludCBtYWluKCkKewogICAgdmVjdG9yPGludD4gYXJyID0geyAxMiwgMTEsIDEzLCA1LC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