Typorithm · easy

Gnome Sort

▷ Interactive algorithm labgnome-sortsortingadjacent-swapsinsertion-sortquadratic-time
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Gnome Sort

0%

Sorting Algorithms

Gnome Sort walks forward through ordered pairs and steps backward whenever it swaps an out-of-order pair.

Gnome Sort feels like Insertion Sort expressed through adjacent swaps.

If the current pair is ordered, the pointer moves right.

If the pair is out of order, the algorithm swaps it and steps left.

Stepping left lets a small value keep moving back until it reaches its insertion position.

The algorithm is easy to trace but has O(n^2) worst-case time.

Preparing algorithm lab…
01

Compare arr[i - 1] and arr[i].

02

Move right when ordered.

03

Swap and move left when out of order.

04

Adjacent strict swaps make it stable.

05

Worst-case time is O(n^2).

function gnomeSort(arr) {
  let i = 1;

  while (i < arr.length) {
    if (i === 0 || arr[i - 1] <= arr[i]) {
      i++;
    } else {
      [arr[i - 1], arr[i]] = [arr[i], arr[i - 1]];
      i--;
    }
  }

  return arr;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Start index

Start at index 1 so there is a left neighbor to compare.

let i = 1

2. Walk array

Continue until the pointer walks beyond the last item.

while (i < arr.length)

3. In-order pair

If the pair is in order, move forward.

i === 0 || arr[i - 1] <= arr[i]

4. Step forward

Move right when the local order is fine.

i++

5. Swap backward

Swap an out-of-order adjacent pair.

[arr[i - 1], arr[i]] = [arr[i], arr[i - 1]]

6. Step backward

After swapping, step back to check whether the value must move farther left.

i--

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Gnome Sort: Visual Walkthrough & Practice · Typorithm | ApplyDjinn