DVCQ-P6

Select in linear time

Practice 6 of 6Divide and conquer12 tests

The problem

Return the value that would be at position k if values were sorted, with 0 <= k < n. Use median of medians to choose pivots, so that the method is O(n) even on the worst lists.

select([7, 2, 9, 4, 1], 2)     # 4
select([5, 1, 5, 1, 5, 3], 3)  # 5

The tests pass the larger lists' values as special number objects that count every comparison made with them (<, <=, >, >=; == is not counted). They behave like normal numbers, and max() and min() count too. Return the values you were given, not copies made with int().

  • On every list, your method may make at most 20n comparisons.
  • The comparisons per value must stay flat as the list grows: for a list 32 times longer, at most 25% more per value. Sorting fails this, because it makes about log₂ n comparisons per value.

sorted(), .sort(), heapq and the functions of random are switched off. Lists of 5 values or fewer can be sorted by hand (insertion sort).

Limits

  • Up to 64,000 values. Lists may be sorted, reversed, all equal, or built to beat a simple pivot rule.

Builds on DVCQ-6 Median of medians.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

12 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2The smallestNot run
3The largestNot run
4RepeatsNot run
5One valueNot run
6Negatives, 13 valuesNot run
720,000 in orderNot run
820,000 in reverse orderNot run
920,000 equal valuesNot run
10Built against the middle pivotNot run
1120,000 scattered valuesNot run
12Comparisons per value stay flatNot run