Untitled
unknown
plain_text
9 months ago
2.1 kB
4
Indexable
import java.util.Random;
public class QuickSelect {
public int findKthSmallest(int[] nums, int k) {
// Convert k-th smallest to 0-based index
int targetIndex = k - 1;
int left = 0, right = nums.length - 1;
Random rand = new Random();
while (left <= right) {
// Select a random pivot index
int pivotIndex = left + rand.nextInt(right - left + 1);
// Partition the array and get the pivot's final position
int finalPivotIndex = partition(nums, left, right, pivotIndex);
if (finalPivotIndex == targetIndex) {
return nums[finalPivotIndex]; // Found the k-th smallest element
} else if (finalPivotIndex < targetIndex) {
left = finalPivotIndex + 1; // Search right subarray
} else {
right = finalPivotIndex - 1; // Search left subarray
}
}
return -1; // This should never be reached if k is valid
}
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 all 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] = temp;
}
public static void main(String[] args) {
QuickSelect qs = new QuickSelect();
int[] nums = {3, 2, 1, 5, 6, 4};
int k = 2; // Find the 2nd smallest element
System.out.println("K-th smallest element: " + qs.findKthSmallest(nums, k)); // Output: 2
}
}
Editor is loading...
Leave a Comment