1. public class MergeSort {
    2. public static void main(String[] args) {
    3. int[] arr = {4 , 8 , 9 , 6 , 7 , 3 , 5 , 1 , 2 , 0};
    4. int length;
    5. int[] temp = new int[length = arr.length];
    6. mergeSort(arr,0,length-1,temp);
    7. System.out.println(Arrays.toString(arr));
    8. }
    9. public static void mergeSort(int[] arr , int left , int right , int[] temp) {
    10. if (left<right) {
    11. int mid = (left + right) / 2 ;
    12. mergeSort(arr,left,mid,temp);
    13. mergeSort(arr,mid+1,right,temp);
    14. merge(arr,left,right,temp);
    15. }
    16. }
    17. public static void merge(int[] arr , int left , int right , int[] temp) {
    18. int l = left;
    19. int mid = (left + right) / 2;
    20. int r = mid + 1;
    21. int tempIndex = left;
    22. while(l <= mid && r <= right) {
    23. if (arr[l] < arr[r]) {
    24. temp[tempIndex] = arr[l];
    25. tempIndex++;
    26. l++;
    27. }else {
    28. temp[tempIndex] = arr[r];
    29. tempIndex++;
    30. r++;
    31. }
    32. }
    33. while (l <= mid){
    34. temp[tempIndex] = arr[l];
    35. tempIndex++;
    36. l++;
    37. }
    38. while(r <= right) {
    39. temp[tempIndex] = arr[r];
    40. tempIndex++;
    41. r++;
    42. }
    43. //if (right + 1 - left >= 0) System.arraycopy(temp, left, arr, left, right + 1 - left);
    44. for (int i = left; i <= right; i++) {
    45. arr[i] =temp[i];
    46. }
    47. }