Untitled

 avatar
unknown
plain_text
16 days ago
1.7 kB
3
Indexable
import java.util.Random;

public class QuickSelect {
    public int findKthSmallest(int[] nums, int k) {
        // k-th smallest corresponds to index k - 1 (0-based)
        return quickSelect(nums, 0, nums.length - 1, k - 1);
    }

    private int quickSelect(int[] nums, int left, int right, int k) {
        Random rand = new Random();

        // Choose a random pivot between left and right
        int pivotIndex = left + rand.nextInt(right - left + 1);

        // Partition the array around the pivot
        int finalPivotIndex = partition(nums, left, right, pivotIndex);

        if (finalPivotIndex == k) {
            return nums[finalPivotIndex]; // Found the k-th smallest
        } else if (finalPivotIndex < k) {
            return quickSelect(nums, finalPivotIndex + 1, right, k); // Search right
        } else {
            return quickSelect(nums, left, finalPivotIndex - 1, k); // Search left
        }
    }

    private int partition(int[] nums, int left, int right, int pivotIndex) {
        int pivotValue = nums[pivotIndex];
        // Move pivot to the end
        swap(nums, pivotIndex, right);
        int storeIndex = left;

        // Move elements smaller than pivot to the left
        for (int i = left; i < right; i++) {
            if (nums[i] < pivotValue) {
                swap(nums, i, storeIndex);
                storeIndex++;
            }
        }

        // Move pivot to its final position
        swap(nums, storeIndex, right);
        return storeIndex;
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j]
Leave a Comment