exmkg

Untitled

Dec 16th, 2024
9
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.93 KB | None | 0 0
  1. class Solution {
  2.     public int[] sortArray(int[] nums) {
  3.         MergeSort(nums, 0, nums.length - 1);
  4.         return nums;
  5.     }  
  6.  
  7.     public static void MergeSort(int[] arr, int left, int right) {
  8.         if (left == right) return;
  9.         int mid = (left + right) / 2;
  10.         MergeSort(arr, left, mid);
  11.         MergeSort(arr, mid + 1, right);
  12.         Merge(arr, left, right);
  13.     }
  14.  
  15.     public static void Merge(int[] arr, int left, int right) {
  16.         int len = right - left + 1;
  17.         int[] tmp = new int[len];
  18.         int mid = (left + right) / 2;
  19.         for (int k = 0, i = left, j = mid + 1; k < len; k++) {
  20.             if (i > mid) tmp[k] = arr[j++];
  21.             else if (j > right) tmp[k] = arr[i++];
  22.             else if (arr[i] < arr[j]) tmp[k] = arr[i++];
  23.             else tmp[k] = arr[j++];
  24.         }
  25.         for (int k = 0, i = left; k < len; k++, i++) {
  26.             arr[i] = tmp[k];
  27.         }
  28.     }
  29. }
  30.  
Add Comment
Please, Sign In to add comment