Challenge: The k-th Smallest
Completed
Print the k-th smallest number (k = 1 means the smallest). Use selection sort, but stop after k rounds – you don't need to sort the whole array.
Input
Line 1: n k (1 ≤ k ≤ n). Line 2: n whole numbers.
Output
The k-th smallest number.
Example
Input
6 2 7 3 9 3 1 8
Output
3
Editor
Java
Hints
Round i puts the i-th smallest number at index i.
After k rounds the answer is at a[k - 1].
Solution explanation
k rounds of up to n checks: O(n·k) – much less than O(n²) when k is small.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), k = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = sc.nextInt();
for (int i = 0; i < k; i++) { // only k rounds
int min = i;
for (int j = i + 1; j < n; j++) if (a[j] < a[min]) min = j;
int t = a[i]; a[i] = a[min]; a[min] = t;
}
System.out.println(a[k - 1]);
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module