public class MergeSort {public static void main(String[] args) {int[] arr = {4 , 8 , 9 , 6 , 7 , 3 , 5 , 1 , 2 , 0};int length;int[] temp = new int[length = arr.length];mergeSort(arr,0,length-1,temp);System.out.println(Arrays.toString(arr));}public static void mergeSort(int[] arr , int left , int right , int[] temp) {if (left<right) {int mid = (left + right) / 2 ;mergeSort(arr,left,mid,temp);mergeSort(arr,mid+1,right,temp);merge(arr,left,right,temp);}}public static void merge(int[] arr , int left , int right , int[] temp) {int l = left;int mid = (left + right) / 2;int r = mid + 1;int tempIndex = left;while(l <= mid && r <= right) {if (arr[l] < arr[r]) {temp[tempIndex] = arr[l];tempIndex++;l++;}else {temp[tempIndex] = arr[r];tempIndex++;r++;}}while (l <= mid){temp[tempIndex] = arr[l];tempIndex++;l++;}while(r <= right) {temp[tempIndex] = arr[r];tempIndex++;r++;}//if (right + 1 - left >= 0) System.arraycopy(temp, left, arr, left, right + 1 - left);for (int i = left; i <= right; i++) {arr[i] =temp[i];}}
