SMALLTALK LAB
Quickselect: find the kth value without sorting everything
Partition around a pivot, keep only the useful bucket, and translate ranks correctly. Build a non-mutating three-way Quickselect, handle duplicates, prove its invariant and test every rank against a sorted oracle.
Before you begin
Use a native Squeak 6.1 Workspace. Select one complete checkpoint and choose Print it. All eight expressions run independently without installed classes or packages. Inputs here are finite collections of ordinary numbers with a stable total order under < and =; exclude NaN and mutually incomparable values. Ranks are one-based integers. Use Do it for the separate Morphic board, setting stage from 0 through 4.
These are native Squeak 6.1 examples. Each checkpoint is independent: open the download as text, copy one complete expression into Workspace and choose Print it. Do not file in the checkpoint collection as a class definition.
01 - Ask for a rank, not a fully sorted collection
The kth smallest value is the value at position k in ascending order. Squeak uses one-based positions: k = 1 means the minimum. Repeated values occupy separate positions. Sorting gives an easy reference answer, but Quickselect will discard irrelevant partitions instead of sorting everything.
| values sorted |
values := #(7 2 9 4 7 1 8 3 6 5).
sorted := values sorted.
{sorted asArray. sorted at: 6. sorted at: 8}Expected: #(#(1 2 3 4 5 6 7 7 8 9) 6 7)

Try it: The two 7s occupy ranks 7 and 8. Selection returns a value, not its original index.
02 - Partition around one pivot in one scan
Choose the first value as pivot. Put every item into exactly one of three buckets: less than, equal to, or greater than the pivot. The buckets preserve the input order internally, but they are not sorted. Keeping equals together prevents repeated pivot values from forcing unnecessary rounds.
| current pivot lower equal higher |
current := #(7 2 9 4 7 1 8 3 6 5).
pivot := current first.
lower := OrderedCollection new.
equal := OrderedCollection new.
higher := OrderedCollection new.
current do: [:item |
item < pivot
ifTrue: [lower add: item]
ifFalse: [item = pivot
ifTrue: [equal add: item]
ifFalse: [higher add: item]]].
{pivot. lower asArray. equal asArray. higher asArray}Expected: #(7 #(2 4 1 3 6 5) #(7 7) #(9 8))

Try it: Check that the bucket sizes add to ten and every item satisfies its bucket comparison.
03 - Turn bucket sizes into rank intervals
If L items are smaller and E items equal the pivot, sorted ranks L+1 through L+E all contain the pivot. A target rank at most L belongs on the left; a target above L+E belongs on the right. These three intervals are exhaustive and do not overlap.
| current pivot lower equal higher classify |
current := #(7 2 9 4 7 1 8 3 6 5).
pivot := current first.
lower := OrderedCollection new.
equal := OrderedCollection new.
higher := OrderedCollection new.
current do: [:item |
item < pivot
ifTrue: [lower add: item]
ifFalse: [item = pivot
ifTrue: [equal add: item]
ifFalse: [higher add: item]]].
classify := [:rank |
rank <= lower size
ifTrue: [#left]
ifFalse: [rank <= (lower size + equal size)
ifTrue: [#equal] ifFalse: [#right]]].
{lower size + 1. lower size + equal size.
classify value: 6. classify value: 7.
classify value: 8. classify value: 9}Expected: #(7 8 left equal equal right)

Try it: A target equal to the last equal-bucket rank is already solved. Using < instead of <= there is an off-by-one error.
04 - Rebase the rank when keeping the right bucket
A rank is relative to the current collection. When keeping the right bucket, subtract all L+E discarded positions. When keeping the left bucket, leave the rank unchanged. Here the ninth smallest original value becomes the first smallest of #(9 8), which is 8 even though 9 is stored first.
| current pivot lower equal higher originalRank localRank |
current := #(7 2 9 4 7 1 8 3 6 5).
originalRank := 9. pivot := current first.
lower := OrderedCollection new.
equal := OrderedCollection new.
higher := OrderedCollection new.
current do: [:item |
item < pivot
ifTrue: [lower add: item]
ifFalse: [item = pivot
ifTrue: [equal add: item]
ifFalse: [higher add: item]]].
localRank := originalRank - lower size - equal size.
{higher asArray. localRank.
(higher sorted at: localRank)}Expected: #(#(9 8) 1 8)

Try it: Explain why subtracting only lower size would produce an invalid rank of three for this two-item bucket.
05 - Repeat only on the bucket containing the answer
The loop invariant is that the requested original value equals the rank-th smallest value of current, with 1 <= rank <= current size. Partitioning and rank rebasing preserve it. If rank falls in the equal interval, pivot is the answer. Otherwise the chosen bucket is strictly smaller because the pivot itself is excluded. This proves termination and correctness for a stable total ordering.
| quickselect values |
quickselect := [:items :k |
| current rank answer done pivot lower equal higher |
((k isInteger and: [k >= 1]) and: [k <= items size])
ifFalse: [Error signal: 'Rank must be in 1..size'].
current := items. rank := k. done := false.
[done] whileFalse: [
pivot := current first.
lower := OrderedCollection new.
equal := OrderedCollection new.
higher := OrderedCollection new.
current do: [:item |
item < pivot
ifTrue: [lower add: item]
ifFalse: [item = pivot
ifTrue: [equal add: item]
ifFalse: [higher add: item]]].
rank <= lower size
ifTrue: [current := lower]
ifFalse: [rank <= (lower size + equal size)
ifTrue: [answer := pivot. done := true]
ifFalse: [
rank := rank - lower size - equal size.
current := higher]]].
answer].
values := #(7 2 9 4 7 1 8 3 6 5).
{quickselect value: values value: 1.
quickselect value: values value: 6.
quickselect value: values value: 8.
quickselect value: values value: 10.
values}Expected: #(1 6 7 9 #(7 2 9 4 7 1 8 3 6 5))

Try it: This version allocates buckets and never modifies the original array. Selection does not promise that any output collection has been sorted.
06 - Handle duplicates and reject invalid requests
All-equal input finishes after one partition, regardless of the requested valid rank. Singletons and negative numbers work normally. Empty input has no valid rank, and ranks zero, beyond the end, or non-integer are errors. The error handlers below turn those deliberate failures into printable markers for this checkpoint.
| quickselect |
quickselect := [:items :k |
| current rank answer done pivot lower equal higher |
((k isInteger and: [k >= 1]) and: [k <= items size])
ifFalse: [Error signal: 'Rank must be in 1..size'].
current := items. rank := k. done := false.
[done] whileFalse: [
pivot := current first.
lower := OrderedCollection new.
equal := OrderedCollection new.
higher := OrderedCollection new.
current do: [:item |
item < pivot
ifTrue: [lower add: item]
ifFalse: [item = pivot
ifTrue: [equal add: item]
ifFalse: [higher add: item]]].
rank <= lower size
ifTrue: [current := lower]
ifFalse: [rank <= (lower size + equal size)
ifTrue: [answer := pivot. done := true]
ifFalse: [
rank := rank - lower size - equal size.
current := higher]]].
answer].
{quickselect value: #(4 4 4 4) value: 3.
quickselect value: #(-8) value: 1.
quickselect value: #(-2 5 -2 0) value: 2.
[quickselect value: #() value: 1]
on: Error do: [:error | #rejected].
[quickselect value: #(1 2) value: 0]
on: Error do: [:error | #rejected].
[quickselect value: #(1 2) value: 3]
on: Error do: [:error | #rejected].
[quickselect value: #(1 2) value: 1.5]
on: Error do: [:error | #rejected]}Expected: #(4 -8 -2 rejected rejected rejected rejected)

Try it: Catch Error here only to demonstrate the contract. In application code, do not silently hide unrelated comparison or programming errors.
07 - Measure the first-pivot worst case honestly
An ascending input and a request for its maximum make the first pivot the smallest remaining item every time. The scan sizes are 10, 9, ..., 1, totaling 55 visited items. For n items the sum is n(n+1)/2, so this deterministic implementation has quadratic worst-case time. A well-balanced sequence of partitions instead sums to linear work.
| current rank done pivot lower equal higher visits rounds answer |
current := (1 to: 10) asArray. rank := current size.
done := false. visits := 0. rounds := 0.
[done] whileFalse: [
rounds := rounds + 1. visits := visits + current size.
pivot := current first.
lower := OrderedCollection new.
equal := OrderedCollection new.
higher := OrderedCollection new.
current do: [:item |
item < pivot
ifTrue: [lower add: item]
ifFalse: [item = pivot
ifTrue: [equal add: item]
ifFalse: [higher add: item]]].
rank <= lower size
ifTrue: [current := lower]
ifFalse: [rank <= (lower size + equal size)
ifTrue: [answer := pivot. done := true]
ifFalse: [rank := rank - lower size - equal size.
current := higher]]].
{answer. visits. rounds}Expected: #(10 55 10)

Try it: Uniformly random pivot indices at each round give expected O(n) selection time on fixed input, but still O(n squared) worst case. The code here does not randomize, so it does not claim that expectation.
08 - Test every rank against an independent sorted oracle
For each length from one through six, enumerate every sequence over -1, 0 and 1, including every duplicate pattern and order. Compare every valid rank with a sorted copy. Also test ascending, descending and mixed distinct-value fixtures. This checks 6,051 rank queries across 1,098 arrays. Tests support the proof; they do not replace the invariant.
| quickselect cases digits value sample sorted checks ok |
quickselect := [:items :k |
| current rank answer done pivot lower equal higher |
((k isInteger and: [k >= 1]) and: [k <= items size])
ifFalse: [Error signal: 'Rank must be in 1..size'].
current := items. rank := k. done := false.
[done] whileFalse: [
pivot := current first.
lower := OrderedCollection new.
equal := OrderedCollection new.
higher := OrderedCollection new.
current do: [:item |
item < pivot
ifTrue: [lower add: item]
ifFalse: [item = pivot
ifTrue: [equal add: item]
ifFalse: [higher add: item]]].
rank <= lower size
ifTrue: [current := lower]
ifFalse: [rank <= (lower size + equal size)
ifTrue: [answer := pivot. done := true]
ifFalse: [
rank := rank - lower size - equal size.
current := higher]]].
answer].
cases := OrderedCollection new.
1 to: 6 do: [:length |
0 to: (3 raisedTo: length) - 1 do: [:encoding |
digits := encoding. sample := Array new: length.
1 to: length do: [:index |
sample at: index put: (digits \\ 3) - 1.
digits := digits // 3].
cases add: sample]].
cases add: (1 to: 10) asArray;
add: (1 to: 10) asArray reversed;
add: #(7 2 9 4 7 1 8 3 6 5);
add: #(42); add: #(-9 12); add: #(5 2 8).
checks := 0. ok := true.
cases do: [:items |
sorted := items sorted.
1 to: items size do: [:rank |
value := quickselect value: items value: rank.
checks := checks + 1.
ok := ok & (value = (sorted at: rank))]].
{ok. cases size. checks}Expected: #(true 1098 6051)

Try it: The enumeration uses base-three digits mapped to -1, 0 and 1. Add mixed magnitudes and every boundary rank when adapting the comparator.
Watch the computed states

Download the visual experiment. Select the entire expression and Do it. Change stage := 0. to another supported stage, close the previous window, and run again. The GIF replays those native states. This example needs native Squeak; no new browser playground compatibility is claimed.
Reason about correctness and limits
The rank counts occurrences, not distinct values. The seventh and eighth values can both be 7. A request for the kth distinct value is a different problem.
Only rightward selection changes the local rank: subtract lower size + equal size. Leftward selection preserves it. The current collection remains unsorted, so current at: rank is not generally the answer.
The invariant links the original requested order statistic to the current local rank. Three disjoint buckets preserve this link, and every nonterminal round excludes at least the pivot, ensuring strict shrinkage.
Choosing the first pivot makes worst-case time O(n squared), assuming constant-cost numeric comparison and amortized constant-cost collection insertion. Random pivots selected uniformly at each round justify expected O(n) time on fixed inputs, not a worst-case guarantee. Sorting the whole input usually costs O(n log n).
This teaching version uses O(n) peak live auxiliary bucket storage with garbage collection, not the O(1) auxiliary space of an in-place partition implementation. Total allocated elements over all rounds can be quadratic in the worst case. The exhaustive test suite and visual history use extra memory separately.
Quickselect is useful when you need one or a few ranks. For many queries on unchanged data, sorting once may be simpler and faster overall. This block neither computes an average of two middle values nor returns a stable original index.
Three practice challenges
Select a median with an explicit even-size policy
Use the reusable block to compute a statistical median for #(9 1 4 4 8 2). Which ranks are needed? Explain how your wrapper should handle empty and odd-sized input, and whether this is still expected-linear with the pivot policy used here.
Show solution
For six items, request ranks 3 and 4; both return 4, so their average is 4. For nonempty odd n, select rank (n // 2) + 1. For even n, average selections at n // 2 and (n // 2) + 1 using /, not integer division //. Reject empty input before either call. Two calls retain the same asymptotic bound, but first-pivot selection remains worst-case quadratic. Random uniform pivots would justify expected linear time for the two calls together.
Repair a rank-rebasing bug with a counterexample
A version subtracts lower size but forgets equal size when descending right. Construct a small duplicate-heavy input where the local rank becomes impossible. State the correct rank and explain how the invariant detects the bug.
Show solution
Use #(2 2 1 3) with k = 4. Pivot 2 yields lower #(1), equal #(2 2), higher #(3). The broken update produces rank 3 in a one-element collection. The correct update is 4 - 1 - 2 = 1, returning 3. The invariant demands 1 <= rank <= current size at each round, so this bug is detectable immediately after the bad update. Add the fixture at every valid rank to the oracle suite.
Randomize the pivot and keep tests reproducible
Modify the selection block to accept a Random generator from its caller. Choose a uniform pivot index in 1..current size. Describe which correctness tests should stay unchanged and how you would compare work on sorted input without claiming a deterministic linear bound.
Show solution
Add a third block argument, :rng, and replace pivot := current first with pivot := current at: (rng nextInt: current size). In Squeak, prepare a reproducible generator with rng := Random new. rng seed: 12345. Pass that generator using value:value:value:. Every selected value must still match the sorted oracle, regardless of seed; only the path and work count change. Record visited-item totals over many seeds on a fixed ascending array and compare their distribution with the deterministic n(n+1)/2 count. Uniform random pivot choices give expected O(n) time, while individual unlucky runs can still take O(n squared).
Continue learning
Sorting Visualiser | Binary Search | Collections | Testing
Environment reference: official Squeak documentation. This lesson and its examples are original. Verified using native Squeak 6.1 build 23976 on Linux.