Untitled

 avatar
unknown
plain_text
18 days ago
2.3 kB
2
Indexable
import java.util.Random;
import java.util.Arrays;

public class QuickSelect {
    public int[] findKSmallestElements(int[] nums, int k) {
        if (k <= 0 || k > nums.length) {
            throw new IllegalArgumentException("k must be between 1 and nums.length");
        }

        quickSelect(nums, 0, nums.length - 1, k - 1);

        // Extract the first k elements (they are guaranteed to be the k smallest)
        int[] result = Arrays.copyOfRange(nums, 0, k);

        // Sort the k smallest elements for clarity (optional, depends on the use case)
        Arrays.sort(result);

        return result;
    }

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

        while (left <= right) {
            int pivotIndex = left + rand.nextInt(right - left + 1);
            int finalPivotIndex = partition(nums, left, right, pivotIndex);

            if (finalPivotIndex == k) {
                return; // Found the k-th smallest element, partition is correct
            } else if (finalPivotIndex < k) {
                left = finalPivotIndex + 1; // Narrow to the right subarray
            } else {
                right = finalPivotIndex - 1; // Narrow to the left subarray
            }
        }
    }

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

        for (int i = left; i < right; i++) {
            if (nums[i] < pivotValue) {
                swap(nums, i, storeIndex);
                storeIndex++;
            }
        }

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

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

    public static void main(String[] args) {
        QuickSelect qs = new QuickSelect();
        int[] nums = {7, 10, 4, 3, 20, 15};
        int k = 3; // Find the 3 smallest elements

        int[] result = qs.findKSmallestElements(nums, k);
        System.out.println("K smallest elements: " + Arrays.toString(result));
    }
}
Leave a Comment