← All patterns
29 / 32
Sorting & Selection

Sorting

When you see it

Signal words

If the prompt uses any of these, this pattern should come to mind first.

sortorderedlexicographicearliestlatestcomparegreedy
Practice

Drill this pattern with an AI trainer — reply only with Hint, Next, Lost, or paste your code.

Ask yourself

  1. Would ordering expose adjacency, duplicates, or the next best choice?
  2. Is a custom comparator the core of the problem?
  3. After sorting, can you solve with one pass?

Classic problem

Selection Sort — On each pass, scan the unsorted suffix for its minimum and swap it into the boundary position. Repeat until the array is sorted. O(n²) time, O(1) space.

Input: arr = [5, 2, 8, 1, 6, 3]

Output: [1, 2, 3, 5, 6, 8] — sorted ascending; each pass places the next smallest element.

Watch it run

Common pitfalls

Assuming JavaScript sorts numbers numerically without a comparator.

Mutating input order when the caller expects it preserved.