PRIORITY QUEUES · ARRAY INDEXING
Build a binary min-heap explorer
See how an array-backed min-heap inserts upward, removes downward and always returns the smallest priority first.
Install the small native explorer
Build and inspect an array-backed binary min-heap in native Squeak 6.1. This lesson is a source-guided workshop: install the complete small application, read its core methods in order, and run eight experiments against the same live model. It is not a FIFO queue and not a binary search tree.
- Use a copy of a Squeak 6.1 learning image, with its matching changes and sources files.
- Download the source below. In Squeak’s File List, select priority-queue.st and choose fileIn. A whole chunk-format file belongs in File List, not pasted into a Workspace.
- Open a Workspace, select the launcher in step 1 and choose Do it. Keep the same Workspace for subsequent commands so view refers to the same window.
- To repeat from the beginning, close the window and run step 1 again. Do not repeat a middle step and expect the original fixture.
Prerequisites: classes and methods, collections and basic blocks. The complete model and view are in the download; the excerpts below are method definitions to read in the Browser, not standalone Workspace expressions.
Complete source (.st) · Native SUnit tests (.st) · Complete workshop kit
Native Squeak only. This application has not been installed into the site’s SqueakJS playground. No network services, timers, files, payments or scheduling actions are performed by the application.
01 · Choose priority, not arrival order
A normal FIFO queue removes the oldest item. A priority queue removes the most urgent item according to an ordering rule. Here, smaller integers mean higher priority. The structure knows only integer priorities, not jobs or deadlines.
- File in the complete source before running the launcher. Start with a copy of your learning image.
- Select the launcher in a Workspace and choose Do it. Keep that Workspace open: it remembers view.
- The buttons call model operations immediately. These are native Morphic controls, not a web simulation.
initialize
super initialize.
items := OrderedCollection new.
swaps := 0.
note := 'Empty: no minimum yet.'view := LSPriorityView open.Expected: An empty array has no root, and minimum answers nil. The view is a teaching instrument, not a scheduler.

02 · Store the first priority
An OrderedCollection holds the heap in level order. The first entry is the root. For position i, its parent is i // 2 and its children are 2 * i and 2 * i + 1, if those positions exist. These formulas assume Squeak’s one-based indexing.
- Run the two lines after step 1. The tree and the array show the same single object value.
- The visual tree is calculated from array indices; the model stores no left or right node pointers.
- Parent/child order is the invariant. Siblings do not have to be sorted.
values
^ items asArrayview heap insert: 8.
view changed.Expected: The array contains #(8), and the root displays 8. values returns a fresh Array so callers do not receive the internal collection.

03 · Repair insertion upward
Append the new priority at the last array position, maintaining a complete binary tree. If it is smaller than its parent, exchange the two and continue at the parent. Stop at the root or when the parent is no larger. This is sift-up.
- Read the insert: method from the model class. value isInteger is checked before adding anything.
- The loop sets index to 1 to finish once the local ordering is correct. It does not move the item to the root in that branch.
- The method answers the inserted integer. The note reports exchanges for this operation, not all previous operations.
insert: value
| index parent |
value isInteger ifFalse: [self error: 'Use an integer priority'].
swaps := 0.
items addLast: value.
index := items size.
[index > 1] whileTrue: [
parent := index // 2.
(items at: parent) <= (items at: index)
ifTrue: [index := 1]
ifFalse: [self swap: parent with: index. index := parent]].
note := 'Inserted ', value printString, '; upward swaps: ', swaps printString.
^ valueview heap insert: 3.
view changed.Expected: The array becomes #(3 8). One exchange moved 3 to the root and 8 down.

04 · Notice what a heap does not promise
Insert a longer sequence and look at both views. A heap guarantees that each parent is no larger than its children. It does not guarantee a fully sorted array, a balanced search-tree ordering between siblings, or FIFO order among equal priorities.
- Follow every edge from a parent to a child: the number never decreases.
- The validator visits positions 2 through size, comparing each with the item at index // 2.
- The empty heap and one-element heap are valid because there are no parent/child violations to check.
isValid
^ (2 to: items size) allSatisfy: [:index |
(items at: index // 2) <= (items at: index)]#(11 6 4 9 12) do: [:value | view heap insert: value].
view changed.Expected: The array is #(3 4 9 8 6 11 12). In particular, 9 appears before 8: the heap is valid even though the array is not sorted.

05 · Follow a longer upward path
Insert 1 into the seven-item heap. It is appended at position 8, then exchanges with positions 4, 2 and 1. The path has three edges. Each exchange uses one temporary variable; no values are dropped or invented.
- Read swap:with: and trace the saved temporary value. Assigning one slot before saving it would overwrite data.
- The Insert 1 button intentionally uses a fixed value to make the experiment reproducible.
- It stops adding at 15 items so the tree stays readable. That limit belongs to the view; the model itself has no fixed capacity.
swap: first with: second
| saved |
saved := items at: first.
items at: first put: (items at: second).
items at: second put: saved.
swaps := swaps + 1view insertOne.Expected: The array is #(1 3 9 4 6 11 12 8), and the view reports three upward swaps.

06 · Remove the root, then repair downward
Save the root as the answer. Move the final array entry to position 1 and remove its old slot. At each level choose the smaller existing child. If the parent is larger, exchange them and continue downward. Choosing the larger child would leave a smaller child below a larger parent.
- The empty case returns nil, not an error. The one-item case removes that item without trying to replace position 1.
- right <= items size prevents reading a missing right child. The left child may exist alone.
- The method returns the saved minimum, not the final position or the number of swaps.
removeMinimum
| result index left right child finished |
swaps := 0.
items isEmpty ifTrue: [note := 'Empty: removal answers nil.'. ^ nil].
result := items first.
items size = 1 ifTrue: [items removeLast. note := 'Removed last item: ', result printString. ^ result].
items at: 1 put: items removeLast.
index := 1. finished := false.
[finished] whileFalse: [
left := index * 2. right := left + 1.
left > items size
ifTrue: [finished := true]
ifFalse: [
child := left.
(right <= items size and: [(items at: right) < (items at: left)])
ifTrue: [child := right].
(items at: index) <= (items at: child)
ifTrue: [finished := true]
ifFalse: [self swap: index with: child. index := child]]].
note := 'Removed minimum ', result printString, '; downward swaps: ', swaps printString.
^ resultview removeOne.Expected: The removed value is 1. The replacement 8 moves down through 3 and 4; the heap becomes #(3 4 9 8 6 11 12).

07 · Repeat removal to sort the priorities
The root is always a minimum because every path is nondecreasing. Repeated removal therefore produces a nondecreasing sequence. One remove operation changes the heap; callers who need to keep it must populate a separate heap or copy the data first.
- Use Remove min repeatedly. Watch the replacement last item sink only as far as needed.
- minimum simply reads the first element and does not remove it. It is constant-time for this representation.
- Insertion and removal travel at most the tree height, O(log n) comparisons/exchanges. Growing OrderedCollection storage can occasionally cost O(n); do not confuse the sift bound with a guaranteed per-call allocation bound.
minimum
^ items isEmpty ifTrue: [nil] ifFalse: [items first]view removeOne.Expected: The second removal removes 3, leaving #(4 6 9 8 12 11). The next minimum is 4.

08 · Test the invariant and edge cases
A convincing test checks every intermediate structure, not just the final picture. The supplied SUnit test checks empty removal, exact fixtures, rejection before mutation, duplicates and negative integers, and 30 deterministic 30-item input sequences. Every insertion and removal is followed by an invariant check.
- File in the separate priority-queue-tests.st after the application source. Then Print it: LSPriorityHeapTest suite run.
- Expected: one test run, one passed, zero failures and errors. The many internal checks are assertions, not 1,853 separate SUnit tests.
- Equal integer priorities are permitted, but no stable arrival-order guarantee is provided. To represent actual jobs, use records plus an explicit comparison and a monotonic tie-breaker.
[view heap size > 0] whileTrue: [view removeOne].Expected: The heap is empty again. A further removal safely answers nil. All 1,853 internal assertions, plus the assertion-count check, pass in one SUnit test method.

Watch the eight native states

Check behavior, then extend it
LSPriorityHeapTest suite runThe test contains 1,853 internal assertions and an assertion-count check. It checks ordering after every operation across deterministic inputs, preserves duplicate counts, tests negative values, and confirms invalid text is rejected without changing the model. This is reproducible evidence, not a proof for every possible input.
Try these extensions after saving a copy: return the ordered drain into a new collection; add a peek button; or store an arrival sequence number with every job to make equal priorities stable. A heap is useful for finding the next minimum, but finding or deleting an arbitrary item is not automatically fast.
Production limitations: no job data, stable ties, decrease-key, persistent storage, concurrency protection, or scheduling clock. The view displays the first 15 items. It uses a fixed teaching layout; make the window at least 1000 by 640 pixels. Close the window to clean up.
Compare a stack and FIFO queue · Compare a binary search tree · Learn SUnit testing · Official Squeak documentation