|
| 1 | +package com.thealgorithms.randomized; |
| 2 | + |
| 3 | +/** |
| 4 | + * This class implements the Randomized QuickSort algorithm. |
| 5 | + * It selects a pivot randomly to improve performance on sorted or nearly sorted data. |
| 6 | + * @author Vibhu Khera |
| 7 | + */ |
| 8 | +public final class RandomizedQuickSort { |
| 9 | + |
| 10 | + private RandomizedQuickSort() { |
| 11 | + throw new UnsupportedOperationException("Utility class"); |
| 12 | + } |
| 13 | + |
| 14 | + /** |
| 15 | + * Sorts the array using the randomized quicksort algorithm. |
| 16 | + * |
| 17 | + * @param arr the array to sort |
| 18 | + * @param low the starting index of the array |
| 19 | + * @param high the ending index of the array |
| 20 | + */ |
| 21 | + public static void randomizedQuickSort(int[] arr, int low, int high) { |
| 22 | + if (low < high) { |
| 23 | + int pivotIndex = partition(arr, low, high); |
| 24 | + randomizedQuickSort(arr, low, pivotIndex - 1); |
| 25 | + randomizedQuickSort(arr, pivotIndex + 1, high); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + /** |
| 30 | + * Partitions the array around a pivot chosen randomly. |
| 31 | + * |
| 32 | + * @param arr the array to partition |
| 33 | + * @param low the starting index |
| 34 | + * @param high the ending index |
| 35 | + * @return the index of the pivot after partitioning |
| 36 | + */ |
| 37 | + private static int partition(int[] arr, int low, int high) { |
| 38 | + int pivotIndex = low + (int) (Math.random() * (high - low + 1)); |
| 39 | + int pivotValue = arr[pivotIndex]; |
| 40 | + swap(arr, pivotIndex, high); // Move pivot to end |
| 41 | + int storeIndex = low; |
| 42 | + for (int i = low; i < high; i++) { |
| 43 | + if (arr[i] < pivotValue) { |
| 44 | + swap(arr, storeIndex, i); |
| 45 | + storeIndex++; |
| 46 | + } |
| 47 | + } |
| 48 | + swap(arr, storeIndex, high); // Move pivot to its final place |
| 49 | + return storeIndex; |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * Swaps two elements in the array, only if the indices are different. |
| 54 | + * |
| 55 | + * @param arr the array in which elements are to be swapped |
| 56 | + * @param i the first index |
| 57 | + * @param j the second index |
| 58 | + */ |
| 59 | + private static void swap(int[] arr, int i, int j) { |
| 60 | + // Skip if indices are the same |
| 61 | + if (i == j) { |
| 62 | + return; |
| 63 | + } |
| 64 | + int temp = arr[i]; |
| 65 | + arr[i] = arr[j]; |
| 66 | + arr[j] = temp; |
| 67 | + } |
| 68 | +} |
0 commit comments