Luleå University of Technology
LTU courses · Python · Algorithms
D0012E.
Algorithms and data structures, with proofs and measurements. Sorting with nothing but two stacks, finding three numbers where x + y = z in quadratic time, and a binary search tree that rebuilds parts of itself to stay shallow. Each lab was done in a group of three, with a written report for each.
Course labs
Try each lab
The numbers start in stack U and end sorted in stack R, smallest on top. Anything in the way goes back onto U. Step through it, or pick another input. Lab 1's code, ported to JavaScript.
- 0
- Pushes
- 0
- Pops
- 0
- Comparisons
- Worst case for these 8: n(3n − 1)/2 pushes
| Input | Pushes | Comparisons | Time |
|---|---|---|---|
| Random | 11,973,116 | 7,980,741 | 5.39 s |
| Sorted (the worst case) | 23,998,000 | 15,996,000 | 10.59 s |
| Reverse (the best case) | 7,999 | 3,999 | 0.0035 s |
23,998,000 is exactly 4000 × (3 × 4000 − 1) / 2, the worst case we proved.
Type some different numbers. Both versions answer the same question. The second keeps the numbers it has seen sorted, so each new number needs one pass instead of a check against every pair.
Insert keys one at a time. When a subtree gets more than c of its parent's nodes, that part is rebuilt perfectly balanced and flashes. A plain search tree with the same keys is shown in numbers next to it.
- 0
- Keys
- 0
- Height of D
- 0
- Height of a plain tree
- 0
- Rebuilds
- 0
- Keys moved by rebuilds
| Input | Plain tree | c = 0.55 | c = 0.7 | c = 0.8 | c = 0.99 |
|---|---|---|---|---|---|
| Random | 15.5 | 18.9 | 13.4 | 12.9 | 15.1 |
| Ascending | 3,999.5 | 62.7 | 33.2 | 28.5 | 75.0 |
| Almost sorted | 2,449.0 | 62.4 | 32.7 | 27.9 | 57.1 |
A low c rebuilds too often and a high c lets the tree get deep. Around 0.8 was cheapest in every input we tried.
The lab files as we handed them in. The demos above are ports of these.
What I learned
For the stack sort, a sorted input is the slowest and a reversed one is the fastest. We proved the exact counts first, and the program then counted the same numbers to the last push.
If the numbers seen so far stay sorted, each new number can be checked with two pointers in one pass. That turns Θ(n³) into Θ(n²).
The maximum subarray becomes linear when each half also returns its total, its best start and its best end, so the two halves can be joined without looking at them again.
Rebuilding a subtree costs a lot once, but it doesn't happen often. The constant c decides how often, and the measurements showed where the balance is.