class MergeSort {
public static void mergesort(int[] x) {
mergesort(x, 0, x.length - 1);
}
private static void mergesort(int[] x, int inicio, int fim) {
if (inicio >= fim) return;
int meio = (inicio + fim) / 2;
mergesort(x, inicio, meio);
mergesort(x, meio + 1, fim);
intercala(x, inicio, fim, meio);
}
private static void intercala(int[] x, int inicio, int fim, int meio) {
int[] aux = new int[x.length];
int inicioVetor1 = inicio;
int inicioVetor2 = meio + 1;
int livre = inicio;
while (inicioVetor1 <= meio && inicioVetor2 <= fim) {
if (x[inicioVetor1] <= x[inicioVetor2]) {
aux[livre] = x[inicioVetor1];
inicioVetor1++;
} else {
aux[livre] = x[inicioVetor2];
inicioVetor2++;
}
livre++;
}
for (int i = inicioVetor1; i <= meio; i++) {
aux[livre] = x[i];
livre++;
}
for (int i = inicioVetor2; i <= fim; i++) {
aux[livre] = x[i];
livre++;
}
for (int i = inicio; i <= fim; i++) {
x[i] = aux[i];
}
}
public static void main
(String[] args
) { int[] x = {6, 2, 1, 3, 0};
mergesort(x);
for (int y : x) {
}
}
}
Y2xhc3MgTWVyZ2VTb3J0IHsKCiAgICBwdWJsaWMgc3RhdGljIHZvaWQgbWVyZ2Vzb3J0KGludFtdIHgpIHsKICAgICAgICBtZXJnZXNvcnQoeCwgMCwgeC5sZW5ndGggLSAxKTsKICAgIH0KCiAgICBwcml2YXRlIHN0YXRpYyB2b2lkIG1lcmdlc29ydChpbnRbXSB4LCBpbnQgaW5pY2lvLCBpbnQgZmltKSB7CiAgICAgICAgaWYgKGluaWNpbyA+PSBmaW0pIHJldHVybjsKICAgICAgICBpbnQgbWVpbyA9IChpbmljaW8gKyBmaW0pIC8gMjsKICAgICAgICBtZXJnZXNvcnQoeCwgaW5pY2lvLCBtZWlvKTsKICAgICAgICBtZXJnZXNvcnQoeCwgbWVpbyArIDEsIGZpbSk7CiAgICAgICAgaW50ZXJjYWxhKHgsIGluaWNpbywgZmltLCBtZWlvKTsKICAgIH0KCiAgICBwcml2YXRlIHN0YXRpYyB2b2lkIGludGVyY2FsYShpbnRbXSB4LCBpbnQgaW5pY2lvLCBpbnQgZmltLCBpbnQgbWVpbykgewogICAgICAgIGludFtdIGF1eCA9IG5ldyBpbnRbeC5sZW5ndGhdOwogICAgICAgIGludCBpbmljaW9WZXRvcjEgPSBpbmljaW87CiAgICAgICAgaW50IGluaWNpb1ZldG9yMiA9IG1laW8gKyAxOwogICAgICAgIGludCBsaXZyZSA9IGluaWNpbzsKICAgICAgICB3aGlsZSAoaW5pY2lvVmV0b3IxIDw9IG1laW8gJiYgaW5pY2lvVmV0b3IyIDw9IGZpbSkgewogICAgICAgICAgICBpZiAoeFtpbmljaW9WZXRvcjFdIDw9IHhbaW5pY2lvVmV0b3IyXSkgewogICAgICAgICAgICAgICAgYXV4W2xpdnJlXSA9IHhbaW5pY2lvVmV0b3IxXTsKICAgICAgICAgICAgICAgIGluaWNpb1ZldG9yMSsrOwogICAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICAgICAgYXV4W2xpdnJlXSA9IHhbaW5pY2lvVmV0b3IyXTsKICAgICAgICAgICAgICAgIGluaWNpb1ZldG9yMisrOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGxpdnJlKys7CiAgICAgICAgfQogICAgICAgIGZvciAoaW50IGkgPSBpbmljaW9WZXRvcjE7IGkgPD0gbWVpbzsgaSsrKSB7CiAgICAgICAgICAgIGF1eFtsaXZyZV0gPSB4W2ldOwogICAgICAgICAgICBsaXZyZSsrOwogICAgICAgIH0KICAgICAgICBmb3IgKGludCBpID0gaW5pY2lvVmV0b3IyOyBpIDw9IGZpbTsgaSsrKSB7CiAgICAgICAgICAgIGF1eFtsaXZyZV0gPSB4W2ldOwogICAgICAgICAgICBsaXZyZSsrOwogICAgICAgIH0KICAgICAgICBmb3IgKGludCBpID0gaW5pY2lvOyBpIDw9IGZpbTsgaSsrKSB7CiAgICAgICAgICAgIHhbaV0gPSBhdXhbaV07CiAgICAgICAgfQogICAgfQoKICAgIHB1YmxpYyBzdGF0aWMgdm9pZCBtYWluKFN0cmluZ1tdIGFyZ3MpIHsKICAgICAgICBpbnRbXSB4ID0gezYsIDIsIDEsIDMsIDB9OwogICAgICAgIG1lcmdlc29ydCh4KTsKICAgICAgICBmb3IgKGludCB5IDogeCkgewogICAgICAgICAgICBTeXN0ZW0ub3V0LnByaW50bG4oeSk7CiAgICAgICAgfQogICAgfQp9