Kth Smallest Numbers in Unsorted Array

Find the kth smallest numbers in an unsorted integer array.

Example

Given[3, 4, 1, 2, 5], k =3, the 3rd smallest numbers are[1, 2, 3].

public int kthSmallest(int k, int[] nums) {
    if(nums == null || nums.length == 0) {
        return -1;
    }
    return quickSelect(k, nums, 0, nums.length() - 1);
}
public int quickSelect(int k, int[] nums, int start, int end) {
    if(start > end) {
        return 0;
    }
    int pivot = partition(nums, start, end);
    if(pivot == k - 1) {
        return nums[pivot];
    }
    else if(pivot > k - 1) {
        return quickSelect(k, nums, start, pivot - 1);
    }
    else {
        return quickSelect(k, nums, pivot + 1, end);
    }
}
public int partition(int[] nums, int left, int right) {
    int pivot = nums[left];
    while(left < right) {
        while(left < right && nums[right] > pivot) {
            right--;
        }
        nums[left] = nums[right];
        while(left < right && nums[left] < pivot) {
            left++;
        }
        nums[right] = nums[left];
    }
    nums[left] = pivot;
    return left;
}

results matching ""

    No results matching ""