What you learn today
- Linear search
- Minimum and maximum
- Stop early
The store has an inventory table in the stack: which ingot, how many. Somebody asks for steel. The chip has to find the row – and preferably not read all entries if steel is already in fourth place.
Table with pairs
Each entry has two values. You store them one after the other: hash at address 2i, quantity at 2i + 1. You compute the address with sll addr i 1 – shifting left once is times 2, from bit week.
| i | address | content |
|---|---|---|
| 0 | 0, 1 | iron, 40 |
| 1 | 2, 3 | copper, 45 |
| 2 | 4, 5 | gold, 8 |
| 3 | 6, 7 | steel, 120 |
Linear search
The simplest search goes through the entries in order and compares. Hashes are whole numbers, so beq is safe here:
move found -1
move i 0
search:
sll addr i 1 # address = 2 · i
get value db addr
beq value target hit # stop early
add i i 1
blt i COUNT search
Stopping early
As soon as the entry is found, the chip jumps out of the loop. If steel is in fourth place, it reads four entries instead of six. With a table of 100 entries that saves half on average. If nothing is found, the loop runs to the end and found stays −1.
−1 as “not found” only works if −1 cannot be a real quantity. For values that may become negative, use a separate flag, such as a second register with 0 or 1.
Minimum and maximum
For the minimum min is enough. For the maximum you also want to know which entry it is – max cannot do that. So you compare yourself and remember value and position:
bge maxv value next # not larger: skip
move maxv value
move maxidx i
next:
The starting values pinf and ninf make sure the first real entry always wins.
Searching and minimum/maximum need one pass, i.e. n comparisons. Sorting would need n · (n − 1) / 2. For “what do we have most of?” the search is always the better choice.
Diagram
Exercise
Task
The inventory table is already in the stack (pairs of hash and quantity). target (r0) holds a hash to look for. Write:
found= quantity of the entry looked for, −1 if it is missing; stop the search as soon as it is foundmaxidx= number i of the entry with the largest quantityminv= smallest quantity
Hints
Hint 1
Address of the hash: sll addr i 1, the quantity sits one further.
Hint 2
Found: jump out of the loop, add addr addr 1, get found db addr.
Hint 3
Maximum with position: bge maxv value next, otherwise move maxv value and move maxidx i.
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