// Merge sort in Java
class MergeSort {
void merge(int arr[], int p, int q, int r) {
int n1 = q - p + 1;
int n2 = r - q;
int L[] = new int[n1];
int M[] = new int[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) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
static void printArray(int arr[]) {
int n = arr.length;
for (int i = 0; i < n; ++i)
System.
out.
print(arr
[i
] + " "); }
public static void main
(String args
[]) { int arr[] = { 6, 5, 12, 10, 9, 1 };
MergeSort ob = new MergeSort();
ob.mergeSort(arr, 0, arr.length - 1);
System.
out.
println("Sorted array:"); printArray(arr);
}
}
Ly8gTWVyZ2Ugc29ydCBpbiBKYXZhCgpjbGFzcyBNZXJnZVNvcnQgewogIHZvaWQgbWVyZ2UoaW50IGFycltdLCBpbnQgcCwgaW50IHEsIGludCByKSB7CgogICAgaW50IG4xID0gcSAtIHAgKyAxOwogICAgaW50IG4yID0gciAtIHE7CgogICAgaW50IExbXSA9IG5ldyBpbnRbbjFdOwogICAgaW50IE1bXSA9IG5ldyBpbnRbbjJdOwoKICAgIGZvciAoaW50IGkgPSAwOyBpIDwgbjE7IGkrKykKICAgICAgTFtpXSA9IGFycltwICsgaV07CiAgICBmb3IgKGludCBqID0gMDsgaiA8IG4yOyBqKyspCiAgICAgIE1bal0gPSBhcnJbcSArIDEgKyBqXTsKCiAgICBpbnQgaSwgaiwgazsKICAgIGkgPSAwOwogICAgaiA9IDA7CiAgICBrID0gcDsKICAgIHdoaWxlIChpIDwgbjEgJiYgaiA8IG4yKSB7CiAgICAgIGlmIChMW2ldIDw9IE1bal0pIHsKICAgICAgICBhcnJba10gPSBMW2ldOwogICAgICAgIGkrKzsKICAgICAgfSBlbHNlIHsKICAgICAgICBhcnJba10gPSBNW2pdOwogICAgICAgIGorKzsKICAgICAgfQogICAgICBrKys7CiAgICB9CiAgICB3aGlsZSAoaSA8IG4xKSB7CiAgICAgIGFycltrXSA9IExbaV07CiAgICAgIGkrKzsKICAgICAgaysrOwogICAgfQoKICAgIHdoaWxlIChqIDwgbjIpIHsKICAgICAgYXJyW2tdID0gTVtqXTsKICAgICAgaisrOwogICAgICBrKys7CiAgICB9CiAgfQogIHZvaWQgbWVyZ2VTb3J0KGludCBhcnJbXSwgaW50IGwsIGludCByKSB7CiAgICBpZiAobCA8IHIpIHsKICAgICAgaW50IG0gPSAobCArIHIpIC8gMjsKCiAgICAgIG1lcmdlU29ydChhcnIsIGwsIG0pOwogICAgICBtZXJnZVNvcnQoYXJyLCBtICsgMSwgcik7CiAgICAgIG1lcmdlKGFyciwgbCwgbSwgcik7CiAgICB9CiAgfQoKICBzdGF0aWMgdm9pZCBwcmludEFycmF5KGludCBhcnJbXSkgewogICAgaW50IG4gPSBhcnIubGVuZ3RoOwogICAgZm9yIChpbnQgaSA9IDA7IGkgPCBuOyArK2kpCiAgICAgIFN5c3RlbS5vdXQucHJpbnQoYXJyW2ldICsgIiAiKTsKICAgIFN5c3RlbS5vdXQucHJpbnRsbigpOwogIH0KICBwdWJsaWMgc3RhdGljIHZvaWQgbWFpbihTdHJpbmcgYXJnc1tdKSB7CiAgICBpbnQgYXJyW10gPSB7IDYsIDUsIDEyLCAxMCwgOSwgMSB9OwoKICAgIE1lcmdlU29ydCBvYiA9IG5ldyBNZXJnZVNvcnQoKTsKICAgIG9iLm1lcmdlU29ydChhcnIsIDAsIGFyci5sZW5ndGggLSAxKTsKCiAgICBTeXN0ZW0ub3V0LnByaW50bG4oIlNvcnRlZCBhcnJheToiKTsKICAgIHByaW50QXJyYXkoYXJyKTsKICB9Cn0=