1. Function declaration
Define a sorting function that receives the array to rearrange.
function selectionSort(arr)Typorithm · easy
Step 1 of 35 · intro card
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).
Track the smallest remaining index with `minIndex`.
Search the unsorted tail from `i + 1` to the end.
Swap once after the inner loop finishes.
In-place with O(1) extra space.
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;
}Connect each part of the code to the concept before you type.
Define a sorting function that receives the array to rearrange.
function selectionSort(arr)Each outer loop position becomes the next place to fill with the smallest remaining value.
for (let i = 0; i < arr.length; i++)Start by assuming the current position already holds the smallest remaining value.
let minIndex = iThe inner loop searches only the unsorted part to the right.
for (let j = i + 1; j < arr.length; j++)When a smaller value appears, remember its index instead of swapping immediately.
arr[j] < arr[minIndex]Store where the smallest value is so it can be swapped after the search finishes.
minIndex = jAfter the scan, swap the smallest remaining value into the current position.
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]]Return the array after every position has been selected.
return arrRead 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