Home › Learn › World 1: Array Plains
FREEBubble Sort Machine
Sorting by adjacent swaps, O(n²)
Level 1.6 of Code the Hero, in Array Plains: scan, swap and sort a row of crates.
The idea
Each adjacent swap fixes exactly one out-of-order pair (an inversion), so bubble sort does exactly as many swaps as there are inversions — up to n²/2.
The mission
The market wants the crates lined up from lightest to heaviest. Bubble sort: compare each pair of neighbours and swap them if they're in the wrong order. Repeat pass after pass. Watch the heavy crates bubble to the right!
Goal: Sort the crates from lightest (left) to heaviest (right). Checked when your code ends.
The commands you get
You write real Python, Java or JavaScript. These are the moves the hero understands in this level:
crates.length | How many crates |
crates.get(i) | Read crate i |
crates.swap(i, j) | Swap crate i and crate j |
What it costs
| Time | O(n²) |
| Swaps | = inversions |
| Extra space | O(1) |
How the stars are earned
- Sorted on every test
- At most 2× the minimum swaps
- Minimum swaps (only swap when out of order)
Your code is also checked on hidden inputs, so it has to work for any case, not only the one on screen.
No sign-up. Levels open in order, so if this one is still locked you start at the first level that isn't.
More in Array Plains
- The Heaviest Crate: Linear scan, O(n)
- Reverse the Row: Two pointers, n/2 swaps
- Count the Apples: Counting in one pass, O(n)
- Irrigation Channels: Prefix sums: O(n) build, O(1) query
- Rotate the Row: Rotation by three reversals, O(n)
- Storm Harvester: Kadane's algorithm, O(n)