import java.util.*;
public class Main {
public static void main
(String[] args
) {
int[] arr = {9,8,7,6,-5,-4,-31,2,1};
display(arr);
mergesort(arr);
System.
out.
println("\nOutput:"); display(arr);
}
public static void display(int arr[]) {
for(int value: arr) {
System.
out.
print(value
+ " "); }
}
public static void mergesort(int[] arr) {
divideEtImpera(0,arr.length-1,arr);
}
public static void divideEtImpera(int lo, int hi, int arr[]) {
if(lo == hi) return;
int middle = (lo+hi)>>1;
divideEtImpera(lo,middle, arr);
divideEtImpera(middle+1,hi,arr);
merge(lo,middle,hi,arr);
}
public static void merge(int lo, int m, int hi, int[] vec) {
int i=lo, j=m+1, k = 0;
int aux[] = new int[hi-lo+1];
while(i<=m && j<=hi) {
if(vec[i]<vec[j]) aux[k++] = vec[i++];
else aux[k++] = vec[j++];
}
while(i<=m) aux[k++] = vec[i++];
while(j<=hi) aux[k++] = vec[j++];
k = 0;
for(int index=lo;index<=hi;index++) vec[index] = aux[k++];
}
}
aW1wb3J0IGphdmEudXRpbC4qOwoKcHVibGljIGNsYXNzIE1haW4gewoKICAgcHVibGljIHN0YXRpYyB2b2lkIG1haW4oU3RyaW5nW10gYXJncykgewoKICAgICBpbnRbXSBhcnIgPSB7OSw4LDcsNiwtNSwtNCwtMzEsMiwxfTsKCiAgICAgU3lzdGVtLm91dC5wcmludGxuKCJJbnB1dDoiKTsKICAgICBkaXNwbGF5KGFycik7CiAgICAgbWVyZ2Vzb3J0KGFycik7CiAgICAgU3lzdGVtLm91dC5wcmludGxuKCJcbk91dHB1dDoiKTsKICAgICBkaXNwbGF5KGFycik7CiAgICAgU3lzdGVtLm91dC5wcmludGxuKCJcbiIpOwogICB9CgogICBwdWJsaWMgc3RhdGljIHZvaWQgZGlzcGxheShpbnQgYXJyW10pIHsKCiAgICAgICAgICBmb3IoaW50IHZhbHVlOiBhcnIpIHsKCiAgICAgICAgICAgICAgU3lzdGVtLm91dC5wcmludCh2YWx1ZSArICIgIik7CiAgICAgICAgICB9CiAgIH0KCiAgIHB1YmxpYyBzdGF0aWMgdm9pZCBtZXJnZXNvcnQoaW50W10gYXJyKSB7CiAgICAgICAgICBkaXZpZGVFdEltcGVyYSgwLGFyci5sZW5ndGgtMSxhcnIpOwogICB9CgogICBwdWJsaWMgc3RhdGljIHZvaWQgZGl2aWRlRXRJbXBlcmEoaW50IGxvLCBpbnQgaGksIGludCBhcnJbXSkgewogICAgICAgICAgaWYobG8gPT0gaGkpIHJldHVybjsKICAgICAgICAgIGludCBtaWRkbGUgPSAobG8raGkpPj4xOwogICAgICAgICAgZGl2aWRlRXRJbXBlcmEobG8sbWlkZGxlLCBhcnIpOwogICAgICAgICAgZGl2aWRlRXRJbXBlcmEobWlkZGxlKzEsaGksYXJyKTsKICAgICAgICAgIG1lcmdlKGxvLG1pZGRsZSxoaSxhcnIpOwogICB9CgogICBwdWJsaWMgc3RhdGljIHZvaWQgbWVyZ2UoaW50IGxvLCBpbnQgbSwgaW50IGhpLCBpbnRbXSB2ZWMpIHsKICAgICAgICAgaW50IGk9bG8sIGo9bSsxLCBrID0gMDsKICAgICAgICAgaW50IGF1eFtdID0gbmV3IGludFtoaS1sbysxXTsKICAgICAgICAgd2hpbGUoaTw9bSAmJiBqPD1oaSkgewogICAgICAgICAgICAgaWYodmVjW2ldPHZlY1tqXSkgYXV4W2srK10gPSB2ZWNbaSsrXTsKICAgICAgICAgICAgICAgICAgICAgZWxzZSBhdXhbaysrXSA9IHZlY1tqKytdOwogICAgICAgICB9CiAgICAgICAgIHdoaWxlKGk8PW0pIGF1eFtrKytdID0gdmVjW2krK107CiAgICAgICAgIHdoaWxlKGo8PWhpKSBhdXhbaysrXSA9IHZlY1tqKytdOwogICAgICAgICBrID0gMDsKICAgICAgICAgZm9yKGludCBpbmRleD1sbztpbmRleDw9aGk7aW5kZXgrKykgdmVjW2luZGV4XSA9IGF1eFtrKytdOwogICB9Cn0K