|
| 1 | +import java.util.Random; |
| 2 | + |
| 3 | +public class RandomizedQuickSort { |
| 4 | + |
| 5 | + private static final Random rand = new Random(); |
| 6 | + |
| 7 | + public static void randomizedQuickSort(int[] arr, int low, int high) { |
| 8 | + if (low < high) { |
| 9 | + int pivotIndex = randomizedPartition(arr, low, high); |
| 10 | + randomizedQuickSort(arr, low, pivotIndex - 1); |
| 11 | + randomizedQuickSort(arr, pivotIndex + 1, high); |
| 12 | + } |
| 13 | + } |
| 14 | + |
| 15 | + private static int randomizedPartition(int[] arr, int low, int high) { |
| 16 | + int pivotIndex = low + rand.nextInt(high - low + 1); |
| 17 | + swap(arr, pivotIndex, high); // Move pivot to end |
| 18 | + return partition(arr, low, high); |
| 19 | + } |
| 20 | + |
| 21 | + private static int partition(int[] arr, int low, int high) { |
| 22 | + int pivot = arr[high]; |
| 23 | + int i = low - 1; // index of smaller element |
| 24 | + for (int j = low; j < high; j++) { |
| 25 | + if (arr[j] <= pivot) { |
| 26 | + i++; |
| 27 | + swap(arr, i, j); |
| 28 | + } |
| 29 | + } |
| 30 | + swap(arr, i + 1, high); |
| 31 | + return i + 1; |
| 32 | + } |
| 33 | + |
| 34 | + private static void swap(int[] arr, int i, int j) { |
| 35 | + int temp = arr[i]; |
| 36 | + arr[i] = arr[j]; |
| 37 | + arr[j] = temp; |
| 38 | + } |
| 39 | + |
| 40 | + // Test the algorithm |
| 41 | + public static void main(String[] args) { |
| 42 | + int[] arr = {10, 7, 8, 9, 1, 5}; |
| 43 | + randomizedQuickSort(arr, 0, arr.length - 1); |
| 44 | + System.out.println("Sorted array:"); |
| 45 | + for (int num : arr) { |
| 46 | + System.out.print(num + " "); |
| 47 | + } |
| 48 | + } |
| 49 | +} |
0 commit comments