Selection Sort Visualizer

Interactive visualization of selection sort algorithm with step-by-step code execution

Array Visualization

64
[0]
34
[1]
25
[2]
12
[3]
22
[4]
11
[5]
90
[6]
Current Position: 1 | Checking: 1 | Min Index: 1
Comparisons: 0 | Swaps: 0
Current Position
Current Minimum
Comparing
Swapping
Sorted

Controls

SlowFast

Selection Sort Algorithm

1function selectionSort(array) {
2  const n = array.length;
3  
4  // Outer loop for each position
5  for (let i = 0; i < n - 1; i++) {
6    // Find minimum element in remaining array
7    let minIndex = i;
8    
9    // Inner loop to find minimum
10    for (let j = i + 1; j < n; j++) {
11      // Compare current element with minimum
12      if (array[j] < array[minIndex]) {
13        minIndex = j;
14      }
15    }
16    
17    // Swap minimum element with first element
18    if (minIndex !== i) {
19      [array[i], array[minIndex]] = [array[minIndex], array[i]];
20    }
21  }
22  
23  return array;
24}
Step 1 of 7

Get the length of the array

About Selection Sort

Understanding the fundamentals, properties, and complexity analysis of the selection sort algorithm

What is Selection Sort?

Selection Sort works by finding the minimum element from the unsorted portion and placing it at the beginning. It divides the array into sorted and unsorted portions, gradually building the sorted portion by selecting the smallest remaining element in each iteration.

Advantages

  • Simple and intuitive algorithm
  • In-place sorting (O(1) space)
  • Minimum number of swaps (O(n))
  • Good for small datasets

Disadvantages

  • Poor time complexity O(n²)
  • Not stable (relative order not preserved)
  • No early termination possible
  • Always makes O(n²) comparisons

Properties

Type:Comparison
Stability:Unstable
Best Case:O(n²)
Average Case:O(n²)
Worst Case:O(n²)
Space:O(1)

When to Use

Small Arrays

Efficient for datasets with < 20 elements

Memory Constraints

When O(1) space complexity is required

Minimize Swaps

When swap operations are expensive

Educational Purposes

Teaching basic sorting concepts

Simple Implementation

When code simplicity is priority

Algorithm Steps

1

Find Minimum

Find the smallest element in unsorted portion

2

Swap to Position

Swap minimum with first unsorted element

3

Extend Sorted

Sorted portion grows by one element

4

Repeat Process

Continue with remaining unsorted elements

5

Complete Sort

Process until entire array is sorted