1. Start index
Start at index 1 so there is a left neighbor to compare.
let i = 1Typorithm · easy
Step 1 of 8 · intro card
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.
Compare arr[i - 1] and arr[i].
Move right when ordered.
Swap and move left when out of order.
Adjacent strict swaps make it stable.
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;
}Connect each part of the code to the concept before you type.
Start at index 1 so there is a left neighbor to compare.
let i = 1Continue until the pointer walks beyond the last item.
while (i < arr.length)If the pair is in order, move forward.
i === 0 || arr[i - 1] <= arr[i]Move right when the local order is fine.
i++Swap an out-of-order adjacent pair.
[arr[i - 1], arr[i]] = [arr[i], arr[i - 1]]After swapping, step back to check whether the value must move farther left.
i--Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
Input[5,1,4,2,8]
One temporary value and a fixed number of indices. In-place does not mean zero extra memory. The input array is not counted as extra space.
One reusable value slot. Empty until the next operation needs it.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state