public class Solution {
public static void mergeSort(int[] arr, int l, int r){
if (l >= r)
return;
int mid = (l + r) / 2;
mergeSort(arr, l, mid);
mergeSort(arr, mid+1, r);
merge(arr, l, r);
}
public static void merge(int[] arr, int l, int r) {
int mid = (l + r) / 2;
int temp[] = new int[r-l+1];
int i = l;
int j = mid+1;
int k = 0;
while (i <= mid && j <= r) {
if (arr[i] < arr[j]) {
temp[k] = arr[i];
k++;
i++;
}
else {
temp[k] = arr[j];
j++;
k++;
}
}
while (i <= mid) {
temp[k] = arr[i];
k++;
i++;
}
while (j <= r) {
temp[k] = arr[j];
j++;
k++;
}
for (int t = 0; t < temp.length; t++) {
arr[t + l] = temp[t];
}
}
}
cHVibGljIGNsYXNzIFNvbHV0aW9uIHsKCiAgICBwdWJsaWMgc3RhdGljIHZvaWQgbWVyZ2VTb3J0KGludFtdIGFyciwgaW50IGwsIGludCByKXsKCiAgICAgICAgaWYgKGwgPj0gcikKICAgICAgICAgICAgcmV0dXJuOwogICAgICAgCiAgICAgICAgaW50IG1pZCA9IChsICsgcikgLyAyOwoKICAgICAgICBtZXJnZVNvcnQoYXJyLCBsLCBtaWQpOwoKICAgICAgICBtZXJnZVNvcnQoYXJyLCBtaWQrMSwgcik7CgogICAgICAgIG1lcmdlKGFyciwgbCwgcik7CiAgICB9CgoKICAgIHB1YmxpYyBzdGF0aWMgdm9pZCBtZXJnZShpbnRbXSBhcnIsIGludCBsLCBpbnQgcikgewoKICAgICAgICBpbnQgbWlkID0gKGwgKyByKSAvIDI7CgogICAgICAgIGludCB0ZW1wW10gPSBuZXcgaW50W3ItbCsxXTsKCiAgICAgICAgaW50IGkgPSBsOwogICAgICAgIGludCBqID0gbWlkKzE7CgogICAgICAgIGludCBrID0gMDsKCiAgICAgICAgd2hpbGUgKGkgPD0gbWlkICYmIGogPD0gcikgewoKICAgICAgICAgICAgaWYgKGFycltpXSA8IGFycltqXSkgewoKICAgICAgICAgICAgICAgIHRlbXBba10gPSBhcnJbaV07CiAgICAgICAgICAgICAgICBrKys7CiAgICAgICAgICAgICAgICBpKys7CiAgICAgICAgICAgIH0KCiAgICAgICAgICAgIGVsc2UgewoKICAgICAgICAgICAgICAgIHRlbXBba10gPSBhcnJbal07CiAgICAgICAgICAgICAgICBqKys7CiAgICAgICAgICAgICAgICBrKys7CiAgICAgICAgICAgIH0KICAgICAgICB9CgogICAgICAgIHdoaWxlIChpIDw9IG1pZCkgewogICAgICAgICAgICAgICAgCiAgICAgICAgICAgIHRlbXBba10gPSBhcnJbaV07CiAgICAgICAgICAgIGsrKzsKICAgICAgICAgICAgaSsrOwogICAgICAgIH0KCiAgICAgICAgd2hpbGUgKGogPD0gcikgewoKICAgICAgICAgICAgdGVtcFtrXSA9IGFycltqXTsKICAgICAgICAgICAgaisrOwogICAgICAgICAgICBrKys7CiAgICAgICAgfQoKCiAgICAgICAgZm9yIChpbnQgdCA9IDA7IHQgPCB0ZW1wLmxlbmd0aDsgdCsrKSB7CgogICAgICAgICAgICBhcnJbdCArIGxdID0gdGVtcFt0XTsKICAgICAgICB9CiAgICB9Cn0K