500-Level Challenge: A Custom Sort
We've spent the 500-level learning how subroutines cooperate.
We've passed arguments and returned results, established conventions for shared memory, preserved state across calls, and even passed execution destinations around as values.
Now it's time to put those ideas together.
We're going to write a sorting routine.
But there's a catch.
The sorting routine won't decide what order the values belong in.
Another subroutine will make that decision.
The Challenge
Write a subroutine that sorts an array of integers in place.
The caller supplies two arguments:
- The address of the array.
- The destination of a comparison subroutine.
For example:
PUSH 0x300
PUSH :ascending
CALL :sort
The sorter must use the supplied comparison subroutine to decide whether two elements should exchange places.
That means the same :sort routine should work with different comparison rules.
We'll start with three:
- Ascending — smallest to largest.
- Descending — largest to smallest.
- Absolute value — smallest magnitude to largest magnitude.
You must not write three different sorting routines.
The challenge is to write one sorter that works with all three comparators.
The Array
We'll use the array representation introduced earlier in the course.
The first memory location contains the number of elements. The elements themselves follow immediately afterward.
For example:
| Address | Value | Meaning |
|---|---|---|
$300 |
5 |
Number of elements |
$301 |
8 |
Element 0 |
$302 |
-3 |
Element 1 |
$303 |
12 |
Element 2 |
$304 |
0 |
Element 3 |
$305 |
4 |
Element 4 |
The array begins at $300, but its first element is at $301.
The sorter should read the length from the array itself.
It should not require the caller to supply the length separately.
When sorting finishes, the length and array address should be unchanged. Only the order of the elements should change.
Exchange Sort
We're going to use a particularly simple sorting algorithm called exchange sort.
It works by comparing each element with every element that follows it.
Whenever two elements are out of order, it swaps them.
In pseudocode:
For each position i:
For each later position j:
If array[j] should precede array[i]:
Swap array[i] and array[j].
For an array containing five elements, the comparisons happen in this order:
0 with 1
0 with 2
0 with 3
0 with 4
1 with 2
1 with 3
1 with 4
2 with 3
2 with 4
3 with 4
Each comparison may cause a swap.
An Example
Suppose we want to sort:
5, 2, 4, 1
into ascending order.
We begin by comparing element 0 with each later element.
| Comparison | Swap? | Array afterward |
|---|---|---|
| 0 with 1 | Yes | 2, 5, 4, 1 |
| 0 with 2 | No | 2, 5, 4, 1 |
| 0 with 3 | Yes | 1, 5, 4, 2 |
Element 0 now contains the smallest value.
Next, we compare element 1 with every element after it.
| Comparison | Swap? | Array afterward |
|---|---|---|
| 1 with 2 | Yes | 1, 4, 5, 2 |
| 1 with 3 | Yes | 1, 2, 5, 4 |
Finally:
| Comparison | Swap? | Array afterward |
|---|---|---|
| 2 with 3 | Yes | 1, 2, 4, 5 |
The array is sorted.
Notice that we didn't need to move elements into temporary arrays or shift entire sections of memory.
We just compared two values and, when necessary, swapped them.
Is this a good sorting algorithm?
Not particularly!
Exchange sort is easy to understand, but it performs a lot of unnecessary comparisons.
For an array containing N elements, exchange sort always performs N * (N - 1) / 2 comparisons.
With five elements, that's 4 + 3 + 2 + 1 = 10 comparisons.
With a hundred elements, it's already 4,950 comparisons, even if the array is sorted before we begin.
There are plenty of other sorting algorithms:
- **Bubble sort** repeatedly compares adjacent elements.
- **Selection sort** finds the next best element and moves it into place.
- **Insertion sort** builds a sorted section one element at a time.
- **Quicksort** partitions an array around a pivot.
- **Merge sort** divides an array into smaller pieces and merges the sorted results.
Some are simpler, some are faster, and some are better suited to particular situations.
We're using exchange sort because its mechanics are simple enough that we can concentrate on something else:
**Making the sorting routine reusable.**
We'll return to questions of efficiency in Level 600.
The Comparator
The sorter doesn't know whether we're sorting in ascending order, descending order, or some other order.
Instead, it asks a comparator.
A comparator is a subroutine that receives two integers and returns one integer.
Its interface is:
| Position | Direction | Value |
|---|---|---|
| 1 | Argument | Left value |
| 2 | Argument | Right value |
| 1 | Result | Swap decision |
The result is:
| Result | Meaning |
|---|---|
0 |
Keep the elements in their current order. |
1 |
Exchange the elements. |
For ascending order:
left = 8
right = 3
8 should come after 3.
Result = 1
But:
left = 3
right = 8
3 should come before 8.
Result = 0
For descending order, those decisions are reversed.
For absolute-value order:
left = -9
right = 4
abs(-9) = 9
abs(4) = 4
Result = 1
The comparator doesn't perform the swap itself.
It only makes the decision.
The sorter remains responsible for exchanging the values.
Calling the Comparator
Suppose the sorter has already loaded the two values it wants to compare.
It can call the comparator like this:
PUSH #left
PUSH #right
CALL #comparator
POP #swap
Here, #comparator refers to a memory location containing the execution destination supplied by the caller.
The sorter doesn't need to know which comparator that destination identifies.
It only needs to know the comparator's interface.
That's the whole point of a callback.
The Sorter's Interface
Your sorting routine must accept:
| Position | Argument | Description |
|---|---|---|
| 1 | Array address | Address of the array's length field. |
| 2 | Comparator destination | Subroutine that decides whether two values should be swapped. |
It sorts the array in place and returns no values.
The caller can therefore write:
PUSH 0x300
PUSH :ascending
CALL :sort
or:
PUSH 0x300
PUSH :descending
CALL :sort
or:
PUSH 0x300
PUSH :absolute
CALL :sort
Nothing inside :sort should need to change.
The sorting routine must also work with arrays of different lengths.
An empty array or an array containing just one element is already sorted. Neither should invoke the comparator.
Your Program
Build a program containing:
- An integer array stored in ordinary memory.
- A reusable
:sortsubroutine implementing exchange sort. - An ascending comparator.
- A descending comparator.
- An absolute-value comparator.
- Code that calls the sorter and displays the resulting array.
Your sorter should use the callback for every ordering decision.
It may use ordinary comparisons to control its loops, but it must not contain hardcoded rules for ascending, descending, or absolute-value ordering.
Each comparator must follow the same argument and result convention.
Remember that Scratch belongs to the caller.
Your sorter cannot assume that its working values will survive a callback.
You may choose your own memory locations and organize the implementation however you like.
Test Your Sorter
Start with this array:
8, -3, 12, 0, 4
Try each comparator.
| Comparator | Expected result |
|---|---|
| Ascending | -3, 0, 4, 8, 12 |
| Descending | 12, 8, 4, 0, -3 |
| Absolute value | 0, -3, 4, 8, 12 |
Restore the original array before testing the next comparator.
Then try an array containing duplicates:
5, 2, 5, -2, 0
| Comparator | Expected result |
|---|---|
| Ascending | -2, 0, 2, 5, 5 |
| Descending | 5, 5, 2, 0, -2 |
For absolute-value sorting, elements with equal magnitudes may remain in either order.
Also test:
- An empty array.
- An array containing one element.
- An array that's already sorted.
- An array whose elements are all equal.
Your sorter should handle all of them without accessing memory outside the array.
Stuck?
Try solving the challenge yourself before opening these.
The hints become progressively more specific. Start at the top and only open as many as you need.
How should I organize the loops?
Exchange sort uses two indices.
The outer index, i, identifies the element currently being placed.
The inner index, j, examines every element after i.
For an array of length N:
i = 0
While i < N - 1:
j = i + 1
While j < N:
Compare elements i and j.
Possibly swap them.
j = j + 1
i = i + 1
Still stuck?
The inner loop can use BLT to decide whether another comparison is needed.
:inner
BLT :compare #j #length
JUMP :next_outer
The outer loop needs a similar boundary check.
You can also skip the entire algorithm when the array contains fewer than two elements.
How do I find the two elements?
The array address points to its length field.
Element 0 is one location after that address.
Element i is therefore at:
array address + 1 + i
The same calculation works for element j.
You could store those two addresses in memory and access the elements indirectly.
Still stuck?
Suppose you reserve two Scratch locations for the addresses:
#left_ptr $010
#right_ptr $011
#left [$010]
#right [$011]
Then calculate the element addresses:
ADD #left_ptr #base 1
ADD #left_ptr #left_ptr #i
ADD #right_ptr #base 1
ADD #right_ptr #right_ptr #j
#left and #right now refer to the selected elements.
Notice that the aliases contain complete indirect operands.
How do I exchange the elements?
You don't need to implement the exchange manually.
NCL already has an instruction that exchanges the values of two locations.
Since the two element operands are indirect, it can operate directly on the array.
Still stuck?
Use:
SWAP #left #right
This exchanges the two selected integers.
It doesn't exchange the pointers themselves.
How do I call the comparator?
The caller supplies a destination, not the name of a particular comparator.
Your sorter should store that destination somewhere it can read later.
Then it can use CALL with that memory location as its operand.
Still stuck?
For example:
#comparator $012
#swap $013
Once #comparator contains the supplied destination:
PUSH #left
PUSH #right
CALL #comparator
POP #swap
You can then test #swap to decide whether to execute SWAP.
Remember that CALL #comparator uses the destination stored in that location.
CALL [#comparator] is not the same thing, and symbols cannot be nested inside indirect operands.
Why does my sorter stop working with some comparators?
Think about which memory locations the comparator is allowed to modify.
A comparator may use Scratch for its own arguments, calculations, and results.
Your sorter is also using Scratch to remember its loop indices, element pointers, and callback destination.
What happens if the comparator overwrites one of those values?
The sorter must preserve anything it still needs after the callback returns.
Still stuck?
Save live Scratch values before calling the comparator.
For example:
PUSH #i
PUSH #j
PUSH #left_ptr
PUSH #right_ptr
PUSH #comparator
Then push the callback arguments and call it.
After retrieving the callback result, restore the saved values in reverse order:
POP #comparator
POP #right_ptr
POP #left_ptr
POP #j
POP #i
This example saves only some of the sorter's possible state.
You must also preserve any other Scratch values that are still needed after the call.
Be careful about the order: the comparator's result must be removed from the stack before restoring the saved values.
How do I write the ascending comparator?
The comparator receives two values.
It should return 1 if the left value is greater than the right value.
Otherwise, it returns 0.
You don't need to know anything about the array or the sorting loops.
Still stuck?
One implementation is:
:ascending
POP $001
POP $000
BGT :ascending_swap $000 $001
PUSH 0
RET
:ascending_swap
PUSH 1
RET
The right argument is popped first because it was pushed last.
Descending order can use the opposite comparison.
Absolute-value order can calculate the magnitudes before comparing them.
Show me one solution
There are several ways to arrange the program.
Here's one implementation.
It uses Scratch for the sorter's working state and saves that state around each callback.
The comparator subroutines are deliberately free to use Scratch themselves.
-- Custom Sort
-- Change this to :descending or :absolute
-- to test another comparison rule.
#order :ascending
-- Array layout
#array 0x300
-- Sorter state
#base $010
#length $011
#comparator $012
#i $013
#j $014
#left_ptr $015
#right_ptr $016
#swap $017
-- Indirect array elements
#left [$015]
#right [$016]
-- Display state
#display_ptr $020
#display_len $021
#display_i $022
#display_val [$020]
-- Prepare the array.
MOVE $300 5
MOVE $301 8
MOVE $302 -3
MOVE $303 12
MOVE $304 0
MOVE $305 4
-- Sort the array.
PUSH #array
PUSH #order
CALL :sort
-- Display the result.
MOVE #display_len $300
MOVE #display_i 0
:display_loop
BGE :done #display_i #display_len
ADD #display_ptr #array 1
ADD #display_ptr #display_ptr #display_i
D.TXT #display_val
D.TXT "\r\n"
ADD #display_i #display_i 1
JUMP :display_loop
:done
D.BLT
JUMP :end
-- Sort an array in place.
--
-- Arguments:
-- array address
-- comparator destination
--
-- Returns:
-- nothing
:sort
POP #comparator
POP #base
-- Read the length from the array header.
MOVE #left_ptr #base
MOVE #length #left
-- Arrays with fewer than two elements
-- are already sorted.
BLT :sort_done #length 2
MOVE #i 0
:outer
SUB #swap #length 1
BGE :sort_done #i #swap
ADD #j #i 1
:inner
BGE :next_outer #j #length
-- Select the two array elements.
ADD #left_ptr #base 1
ADD #left_ptr #left_ptr #i
ADD #right_ptr #base 1
ADD #right_ptr #right_ptr #j
-- Preserve the sorter's live Scratch.
PUSH #base
PUSH #length
PUSH #comparator
PUSH #i
PUSH #j
PUSH #left_ptr
PUSH #right_ptr
-- Ask the comparator whether to swap.
PUSH #left
PUSH #right
CALL #comparator
POP #swap
-- Restore the sorter's state.
POP #right_ptr
POP #left_ptr
POP #j
POP #i
POP #comparator
POP #length
POP #base
-- Act on the comparator's decision.
BEQ :no_swap #swap 0
SWAP #left #right
:no_swap
ADD #j #j 1
JUMP :inner
:next_outer
ADD #i #i 1
JUMP :outer
:sort_done
RET
-- Ascending comparator.
-- Swap when left > right.
:ascending
POP $001
POP $000
BGT :ascending_swap $000 $001
PUSH 0
RET
:ascending_swap
PUSH 1
RET
-- Descending comparator.
-- Swap when left < right.
:descending
POP $001
POP $000
BLT :descending_swap $000 $001
PUSH 0
RET
:descending_swap
PUSH 1
RET
-- Absolute-value comparator.
-- Swap when abs(left) > abs(right).
:absolute
POP $001
POP $000
ABS $002 $000
ABS $003 $001
BGT :absolute_swap $002 $003
PUSH 0
RET
:absolute_swap
PUSH 1
RET
:end
Changing the Order
Near the beginning of the program, change:
#order :ascending
to:
#order :descending
Run the program again.
The same sorter now produces:
12
8
4
0
-3
Change it again:
#order :absolute
This time, the result is:
0
-3
4
8
12
We haven't changed a single instruction inside :sort.
Why Save So Much State?
Notice what happens immediately before the callback:
PUSH #base
PUSH #length
PUSH #comparator
PUSH #i
PUSH #j
PUSH #left_ptr
PUSH #right_ptr
All seven values belong to the sorter's working state.
The comparator is free to modify Scratch, including the locations where those values were stored.
We therefore save them on the stack.
After the comparator returns its decision, we restore them in reverse order.
Only then do we execute:
SWAP #left #right
By that point, both pointers have been restored, so the indirect operands once again identify the correct array elements.
Without that preservation, a comparator that happened to use the same Scratch locations could cause the sorter to read or modify the wrong memory.
This is why the calling convention matters.
What Makes This Reusable?
The sorter knows:
- where the array begins;
- how to read its length;
- how to visit pairs of elements;
- how to call a comparator;
- how to swap two elements.
It does not know what ascending, descending, or absolute-value order means.
The comparators know how to compare two integers.
They do not know where the array lives, how many elements it contains, or how the sorting algorithm works.
Each subroutine has one responsibility.
They cooperate through their interfaces.
Going Further
Selection sort
Exchange sort works, but it can perform quite a few swaps.
Every time it finds a better candidate, it immediately exchanges the two elements.
What if we remembered the best candidate and waited until we'd examined all the remaining elements before swapping?
This approach is called selection sort.
Try modifying your sorting routine to use selection sort while keeping the same arguments and comparator interface.
Compare the algorithms
Exchange sort
For each position i:
For each later position j:
If array[j] should precede array[i]:
Swap array[i] and array[j].
Selection sort
For each position i:
best = i
For each later position j:
If array[j] should precede array[best]:
best = j
If best != i:
Swap array[i] and array[best].
Both algorithms perform the same number of comparisons, but selection sort performs at most one swap per outer iteration.
Notice that the comparator interface hasn't changed.
Only the sorting algorithm has.
Can you make your new sorter work with all three comparators without modifying any of them?
Which algorithm performs fewer swaps on an array that's already sorted?
What about an array in reverse order?
We'll explore questions like these in Level 600.
That's the end of the 500-level.
We've gone from making our first subroutine calls to building routines that accept arguments, return results, preserve their callers' state, use stack frames, dispatch through tables, and call other routines supplied at runtime.
In this challenge, we brought those ideas together.
Our sorting routine doesn't need to know how values should be ordered. It delegates that decision to another subroutine through a shared interface.
And because the interface stays the same, we can change the comparison rules without changing the sorter.
We can even replace the sorting algorithm itself without changing the comparators or the code that calls it.
That's what reusable subroutines make possible.
But there's another question we haven't spent much time asking:
How much work is our program doing?
Our exchange sort gets the job done, but it performs plenty of comparisons and potentially plenty of swaps.
Could we do better?
In NCL 601: The Cost of Code, we'll start looking at what our programs actually cost to execute.