CODE THE HERO

Home › Learn › World 1: Array Plains

FREE

Bubble 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.lengthHow many crates
crates.get(i)Read crate i
crates.swap(i, j)Swap crate i and crate j

What it costs

TimeO(n²)
Swaps= inversions
Extra spaceO(1)

How the stars are earned

  1. Sorted on every test
  2. At most 2× the minimum swaps
  3. 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.

▶ Play this level free

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