Typorithm · easy

Selection Sort

▷ Interactive algorithm labsortingselection-sortmin-indexquadratic-time
Saved on this device
Full lesson · 35 learning steps Open any exercise for focused practice
1

Step 1 of 35 · intro card

Learn Selection Sort

0%

Sorting Algorithms

Selection Sort scans the unsorted side, selects the smallest value, and puts it into the next sorted position.

Selection Sort splits the array into a sorted left side and an unsorted right side. The outer loop index i marks the first unsorted position.

At the start of each pass, minIndex points at i. The inner loop scans from i + 1 to the end and updates minIndex when it finds a smaller value.

Only after the scan finishes does the algorithm swap arr[i] with arr[minIndex]. This grows the sorted left side by one value.

Even if the array is already sorted, the basic version still scans the remaining values, so best, average, and worst time are O(n^2).

Preparing algorithm lab…
01

Track the smallest remaining index with `minIndex`.

02

Search the unsorted tail from `i + 1` to the end.

03

Swap once after the inner loop finishes.

04

In-place with O(1) extra space.

05

Not stable by default because swapping can move equal values past each other.

function selectionSort(arr) {
  for (let i = 0; i < arr.length; i++) {
    let minIndex = i;

    for (let j = i + 1; j < arr.length; j++) {
      if (arr[j] < arr[minIndex]) {
        minIndex = j;
      }
    }

    [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
  }

  return arr;
}

Read the implementation

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

1. Function declaration

Define a sorting function that receives the array to rearrange.

function selectionSort(arr)

2. Outer loop

Each outer loop position becomes the next place to fill with the smallest remaining value.

for (let i = 0; i < arr.length; i++)

3. Minimum index

Start by assuming the current position already holds the smallest remaining value.

let minIndex = i

4. Search remaining values

The inner loop searches only the unsorted part to the right.

for (let j = i + 1; j < arr.length; j++)

5. Find smaller value

When a smaller value appears, remember its index instead of swapping immediately.

arr[j] < arr[minIndex]

6. Update minimum index

Store where the smallest value is so it can be swapped after the search finishes.

minIndex = j

7. Swap into place

After the scan, swap the smallest remaining value into the current position.

[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]]

8. Return sorted array

Return the array after every position has been selected.

return arr

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.

Selection Sort: Visual Walkthrough & Practice · Typorithm | ApplyDjinn