#include <iostream>
using namespace std;
void merge(int arr[], int p, int q, int r) {
int n1 = q - p + 1;
int n2 = r - q;
int L[n1], M[n2];
for (int i = 0; i < n1; i++)
L[i] = arr[p + i];
for (int j = 0; j < n2; j++)
M[j] = arr[q + 1 + j];
int i, j, k;
i = 0;
j = 0;
k = p;
while (i < n1 && j < n2) {
if (L[i] <= M[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = M[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = M[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r) {
if (l < r) {
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
int main() {
int arr[] = {6, 5, 12, 10, 9, 1};
int size = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, size - 1);
cout << "Sorted array: \n";
printArray(arr, size);
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKdm9pZCBtZXJnZShpbnQgYXJyW10sIGludCBwLCBpbnQgcSwgaW50IHIpIHsKICAKICBpbnQgbjEgPSBxIC0gcCArIDE7CiAgaW50IG4yID0gciAtIHE7CgogIGludCBMW24xXSwgTVtuMl07CgogIGZvciAoaW50IGkgPSAwOyBpIDwgbjE7IGkrKykKICAgIExbaV0gPSBhcnJbcCArIGldOwogIGZvciAoaW50IGogPSAwOyBqIDwgbjI7IGorKykKICAgIE1bal0gPSBhcnJbcSArIDEgKyBqXTsKCiAgaW50IGksIGosIGs7CiAgaSA9IDA7CiAgaiA9IDA7CiAgayA9IHA7CgogIHdoaWxlIChpIDwgbjEgJiYgaiA8IG4yKSB7CiAgICBpZiAoTFtpXSA8PSBNW2pdKSB7CiAgICAgIGFycltrXSA9IExbaV07CiAgICAgIGkrKzsKICAgIH0gZWxzZSB7CiAgICAgIGFycltrXSA9IE1bal07CiAgICAgIGorKzsKICAgIH0KICAgIGsrKzsKICB9CgogIHdoaWxlIChpIDwgbjEpIHsKICAgIGFycltrXSA9IExbaV07CiAgICBpKys7CiAgICBrKys7CiAgfQoKICB3aGlsZSAoaiA8IG4yKSB7CiAgICBhcnJba10gPSBNW2pdOwogICAgaisrOwogICAgaysrOwogIH0KfQp2b2lkIG1lcmdlU29ydChpbnQgYXJyW10sIGludCBsLCBpbnQgcikgewogIGlmIChsIDwgcikgewogICAgaW50IG0gPSBsICsgKHIgLSBsKSAvIDI7CgogICAgbWVyZ2VTb3J0KGFyciwgbCwgbSk7CiAgICBtZXJnZVNvcnQoYXJyLCBtICsgMSwgcik7CiAgICBtZXJnZShhcnIsIGwsIG0sIHIpOwogIH0KfQoKdm9pZCBwcmludEFycmF5KGludCBhcnJbXSwgaW50IHNpemUpIHsKICBmb3IgKGludCBpID0gMDsgaSA8IHNpemU7IGkrKykKICAgIGNvdXQgPDwgYXJyW2ldIDw8ICIgIjsKICBjb3V0IDw8IGVuZGw7Cn0KCmludCBtYWluKCkgewogIGludCBhcnJbXSA9IHs2LCA1LCAxMiwgMTAsIDksIDF9OwogIGludCBzaXplID0gc2l6ZW9mKGFycikgLyBzaXplb2YoYXJyWzBdKTsKCiAgbWVyZ2VTb3J0KGFyciwgMCwgc2l6ZSAtIDEpOwoKICBjb3V0IDw8ICJTb3J0ZWQgYXJyYXk6IFxuIjsKICBwcmludEFycmF5KGFyciwgc2l6ZSk7CiAgcmV0dXJuIDA7Cn0K