← Daily Logs
Algorithms

Selection Sort

EasyJun 26, 2026arraysortingin-place

Grow a sorted prefix one slot at a time by pulling the smallest remaining value to the front. Textbook O(n²), but it sorts in place with no extra memory.

The problem

Implement selection sort: take an array of integers and return it sorted in ascending order. `[9, 3, 6, 2, 1, 11]` becomes `[1, 2, 3, 6, 9, 11]`.

The idea behind the algorithm is to repeatedly find the smallest element in the unsorted region and move it to the front, so a sorted prefix grows by one element on every pass.

The approach

The outer loop fixes a slot `left` — the next position to settle. Everything before it is already sorted; everything from `left` onward is still in play. The inner loop walks the rest of the array looking for something smaller.

Rather than recording the index of the minimum and swapping once at the end, I swap eagerly: the moment `arr[left]` is bigger than a later `arr[right]`, I exchange them. By the time the inner loop ends, the smallest of the remaining values has been pulled into `left`, so the sorted prefix extends by one. It's a few more writes than the classic single-swap version, but it lands the same sorted array.

The solution

js
/**
 * @param {Array<number>} arr The input integer array to be sorted.
 * @return {Array<number>}
 */
export default function selectionSort(arr) {
  for(let left = 0; left<= arr.length; left++){
    for(let right = left+1; right<arr.length;right++) {
      if(arr[left]>arr[right]) {
        const temp = arr[left]
        arr[left] = arr[right]
        arr[right] = temp
      }
    }
  }
  return arr
}

Time O(n²)Space O(1)

All entries