Advertisement
exmkg

Untitled

Jan 12th, 2025
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.08 KB | None | 0 0
  1. // Basic Quicksort.
  2. class Solution {
  3.     public int[] sortArray(int[] nums) {
  4.         quickSort(nums, 0, nums.length - 1);
  5.         return nums;
  6.     }
  7.  
  8.     private static void quickSort(int[] arr, int left, int right) {
  9.         if (left >= right) {
  10.             return;
  11.         }
  12.         Random rand = new Random();
  13.         int randIndex = rand.nextInt(left, right + 1);
  14.         swap(arr, left, randIndex);
  15.  
  16.         int pivot = arr[left];
  17.         int storeIndex = left + 1;
  18.         for (int i = left + 1; i <= right; i++) {
  19.             if (arr[i] < pivot) {
  20.                 swap(arr, i, storeIndex);
  21.                 storeIndex++;
  22.             }
  23.         }
  24.         swap(arr, left, storeIndex - 1);
  25.         int l = storeIndex - 2;
  26.         while (l >= left && arr[l] == pivot) l--;
  27.         quickSort(arr, left, l);
  28.         int r = storeIndex;
  29.         while (r <= right && arr[r] == pivot) r++;
  30.         quickSort(arr, r, right);
  31.     }
  32.  
  33.     private static void swap(int[] arr, int i, int j) {
  34.         int tmp = arr[i];
  35.         arr[i] = arr[j];
  36.         arr[j] = tmp;
  37.     }
  38. }
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement