#include <iostream>
#include <ctime>
using namespace std;
void Merge(int A[], int L[], int R[], int nA, int nL, int nR) {
int i = 0, j = 0, k = 0;
while (i < nL && j < nR) {
if (L[i] < R[j]) {
A[k] = L[i];
i++;
} else {
A[k] = R[j];
j++;
}
k++;
}
while (i < nL) {
A[k] = L[i];
i++;
k++;
}
while (j < nR) {
A[k] = R[j];
j++;
k++;
}
}
void Merge_sort(int A[], int n) {
if (n < 2) return;
int mid = n / 2;
int v1 = mid, v2 = n - mid;
int left[v1], right[v2];
for (int i = 0; i < mid; i++) {
left[i] = A[i];
}
for (int i = mid; i < n; i++) {
right[i - mid] = A[i];
}
Merge_sort(left, mid);
Merge_sort(right, n - mid);
Merge(A, left, right, n, mid, n - mid);
}
int main() {
int n, i;
cout << "Enter the size of the array: ";
cin >> n;
int A[n];
cout << "Enter the elements: ";
for (i = 0; i < n; i++) {
cin >> A[i];
}
clock_t start = clock();
Merge_sort(A, n);
clock_t end = clock();
cout << "Sorted array: ";
for (i = 0; i < n; i++) {
cout << A[i] << " ";
}
cout << endl;
double time_taken = double(end - start) / CLOCKS_PER_SEC * 1000;
cout << "Time taken to sort the array: " << time_taken << " ms" << endl;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8Y3RpbWU+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7Cgp2b2lkIE1lcmdlKGludCBBW10sIGludCBMW10sIGludCBSW10sIGludCBuQSwgaW50IG5MLCBpbnQgblIpIHsKICAgIGludCBpID0gMCwgaiA9IDAsIGsgPSAwOwogICAgd2hpbGUgKGkgPCBuTCAmJiBqIDwgblIpIHsKICAgICAgICBpZiAoTFtpXSA8IFJbal0pIHsKICAgICAgICAgICAgQVtrXSA9IExbaV07CiAgICAgICAgICAgIGkrKzsKICAgICAgICB9IGVsc2UgewogICAgICAgICAgICBBW2tdID0gUltqXTsKICAgICAgICAgICAgaisrOwogICAgICAgIH0KICAgICAgICBrKys7CiAgICB9CiAgICB3aGlsZSAoaSA8IG5MKSB7CiAgICAgICAgQVtrXSA9IExbaV07CiAgICAgICAgaSsrOwogICAgICAgIGsrKzsKICAgIH0KICAgIHdoaWxlIChqIDwgblIpIHsKICAgICAgICBBW2tdID0gUltqXTsKICAgICAgICBqKys7CiAgICAgICAgaysrOwogICAgfQp9Cgp2b2lkIE1lcmdlX3NvcnQoaW50IEFbXSwgaW50IG4pIHsKICAgIGlmIChuIDwgMikgcmV0dXJuOwoKICAgIGludCBtaWQgPSBuIC8gMjsKICAgIGludCB2MSA9IG1pZCwgdjIgPSBuIC0gbWlkOwogICAgaW50IGxlZnRbdjFdLCByaWdodFt2Ml07CgogICAgZm9yIChpbnQgaSA9IDA7IGkgPCBtaWQ7IGkrKykgewogICAgICAgIGxlZnRbaV0gPSBBW2ldOwogICAgfQogICAgZm9yIChpbnQgaSA9IG1pZDsgaSA8IG47IGkrKykgewogICAgICAgIHJpZ2h0W2kgLSBtaWRdID0gQVtpXTsKICAgIH0KCiAgICBNZXJnZV9zb3J0KGxlZnQsIG1pZCk7CiAgICBNZXJnZV9zb3J0KHJpZ2h0LCBuIC0gbWlkKTsKICAgIE1lcmdlKEEsIGxlZnQsIHJpZ2h0LCBuLCBtaWQsIG4gLSBtaWQpOwp9CgppbnQgbWFpbigpIHsKICAgIGludCBuLCBpOwogICAgY291dCA8PCAiRW50ZXIgdGhlIHNpemUgb2YgdGhlIGFycmF5OiAiOwogICAgY2luID4+IG47CiAgICBpbnQgQVtuXTsKICAgIGNvdXQgPDwgIkVudGVyIHRoZSBlbGVtZW50czogIjsKICAgIGZvciAoaSA9IDA7IGkgPCBuOyBpKyspIHsKICAgICAgICBjaW4gPj4gQVtpXTsKICAgIH0KCiAgICBjbG9ja190IHN0YXJ0ID0gY2xvY2soKTsKICAgIE1lcmdlX3NvcnQoQSwgbik7CiAgICBjbG9ja190IGVuZCA9IGNsb2NrKCk7CgogICAgY291dCA8PCAiU29ydGVkIGFycmF5OiAiOwogICAgZm9yIChpID0gMDsgaSA8IG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