Searching & Sorting AlgorithmsBeginner LevelStudy Time: 12 mins

Selection Sort Algorithm

Selection Sort divides the input array into a sorted prefix and unsorted suffix, iteratively selecting the minimum value from the unsorted segment and swapping it to the front.

Loading visualizer workspace...

Selection Sort Worked Trace

Sample Input:Input Array: [64, 25, 12, 22, 11]
Step 1

Pass 1 - Find Minimum (11)

Scan indices 0..4 to locate minimum element 11 at index 4. Swap arr[0] (64) with arr[4] (11).

[64, 25, 12, 22, 11] -> Min=11 -> Swap -> [11, 25, 12, 22, 64]
Minimum value 11 is placed in its final sorted position at index 0.
Step 2

Pass 2 - Find Next Minimum (12)

Scan unsorted suffix indices 1..4. Minimum is 12 at index 2. Swap arr[1] (25) with arr[2] (12).

[11, 25, 12, 22, 64] -> Min=12 -> Swap -> [11, 12, 25, 22, 64]
Sorted prefix expands to [11, 12].
Step 3

Pass 3 - Swap 22 and 25

Scan unsorted suffix indices 2..4. Minimum is 22 at index 3. Swap arr[2] (25) with arr[3] (22).

Final Output: [11, 12, 22, 25, 64]
Array is completely sorted in O(N²) time using minimal swaps.

Real-world analogy: Sorting Playing Cards

Min Index
Hover over items for details

Scan your hand for the smallest card and place it first. Then scan the rest for the next smallest and place it second.

  • Min Index= Tracks index of the smallest element in the remaining slice.

Complexity analysis

Scenario Simulator: Dataset Size (N = 500)
Presets:
N = 10N = 10,000
Complexity Curve MapSelection Sort: O(N²) Quadratic Time
Time (t)Size N (500)N = 500O(N²)O(N log N)O(N)O(log N)O(1)Selection Sort N
Time Steps (N=500)

250,000 steps (Quadratic)

O(N²) Quadratic Time

Space Footprint

O(1) In-Place Space

Memory growth rate as N expands.

Performance Rank
Heavy Tier

Relative efficiency rating for large N.

OperationTime ComplexitySpace Complexity
Best / Worst CaseO(N²)O(1)

Code implementations

function selectionSort(arr) {
  const n = arr.length;
  for (let i = 0; i < n; i++) {
    let minIdx = i;
    for (let j = i + 1; j < n; j++) {
      if (arr[j] < arr[minIdx]) minIdx = j;
    }
    [arr[i], arr[minIdx]] = [arr[minIdx], arr[i]];
  }
  return arr;
}

Real-world applications

Case 01

Minimal Write Memory

Makes at most O(N) total swaps, ideal for EEPROM flash memory with limited write cycles.

Interview questions

Topic Knowledge Test & Assessment

10 Questions Assessment

Selection Sort Knowledge & Skill Test

Validate your conceptual understanding, operation mechanics, and core concepts of Selection Sort.