THINK FIRST·CODE LATER

← All labs

Quickselect: the k-th smallest without sorting

Problem

Write QuickSelect. Read n and n integers, then values of k (1 = smallest). For each k, find the k-th smallest element with quickselect: partition with the Lomuto scheme and the last element as pivot; if the pivot lands at index k − 1 it is the answer, otherwise continue in one side only. Work on a fresh copy of the input for each k. Print each pivot and where it lands, the answer and the number of comparisons; finish with the median (element at sorted index (n − 1)/2).

For the input

7
9 3 7 1 8 2 5
4 1 7

the program prints

k = 4:
  pivot 5 lands at index 3
  answer 5 (6 comparisons, check ok)
k = 1:
  pivot 5 lands at index 3
  pivot 2 lands at index 1
  answer 1 (8 comparisons, check ok)
k = 7:
  pivot 5 lands at index 3
  pivot 9 lands at index 6
  answer 9 (8 comparisons, check ok)
Median: 5

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d7-5-data-1.txt

7
9 3 7 1 8 2 5
4 1 7
What your program must print for d7-5-data-1.txt
k = 4:
  pivot 5 lands at index 3
  answer 5 (6 comparisons, check ok)
k = 1:
  pivot 5 lands at index 3
  pivot 2 lands at index 1
  answer 1 (8 comparisons, check ok)
k = 7:
  pivot 5 lands at index 3
  pivot 9 lands at index 6
  answer 9 (8 comparisons, check ok)
Median: 5

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d7-5-data-1.txt

Windows PowerShell does not understand <:

Get-Content d7-5-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.