What you learn today
- Order values
- Swap with registers
- Cost per tick
Five batteries, five charge levels. Which one is the second weakest? Minimum only tells you the weakest. Whoever needs a ranking has to sort – and IC10 has no instruction for it. You build it yourself.
Ordering values: bubble sort
The simplest method always compares two neighbours and swaps them if they are the wrong way round. After one pass the largest value is right at the back. The next pass does not need to touch it any more and is one step shorter.
| Pass | stack 0–4 |
|---|---|
| start | 5 3 9 1 7 |
| 1 | 3 5 1 7 9 |
| 2 | 3 1 5 7 9 |
| 3 | 1 3 5 7 9 |
| 4 | 1 3 5 7 9 |
Swapping with registers
IC10 has no swap. You swap two stack slots through two registers: read both, write back crosswise.
get a db j
add k j 1
get b db k
ble a b next # already in order
poke j b
poke k a
next:
The jump over the swap means: if the two are already in the right order, everything stays as it is. Equal values are not swapped either, hence ble and not blt.
Two loops
The inner loop runs over the pairs with j, the outer one shortens the limit after every pass:
sub limit COUNT 1
outer:
move j 0
inner:
add j j 1
blt j limit inner
sub limit limit 1
bgtz limit outer
Cost per tick
For n values bubble sort compares n · (n − 1) / 2 pairs. Each comparison costs about eight instructions here:
| Values | comparisons | instructions | ticks |
|---|---|---|---|
| 5 | 10 | ~80 | 1 |
| 10 | 45 | ~360 | 3 |
| 20 | 190 | ~1,500 | 12 |
| 50 | 1,225 | ~10,000 | 77 |
The chip pauses after 128 instructions by itself and carries on in the next tick. With 50 values sorting therefore takes almost 40 seconds – and during that time the chip does nothing else.
If you only need the smallest or largest value, do not sort: a search (tomorrow) needs n comparisons instead of n · (n − 1) / 2. Sorting pays off for rankings and the median.
Diagram
Exercise
Task
v0 to v4 (r0–r4) hold five values, they are already in stack 0–4. Sort them in the stack with bubble sort in ascending order and write them back into v0 to v4.
Hints
Hint 1
Inner loop: get a db j, get b db k with k = j + 1, ble a b next, otherwise poke crosswise.
Hint 2
Outer loop: limit starts at COUNT − 1 and gets smaller after every pass.
Hint 3
Finally five get back into the registers.
Quiz
3 questions. You pass from 60 % – the server does the grading.
Complete the day
- Passed the simulator exercise
- Passed the quiz with at least 60 %
Without an account progress is saved in this browser only.
Report a mistake in this lesson
Please sign in to report. Sign in