FlowLab Logo

Selection Sort Visualizer

SlowFast
64
[0]
34
[1]
25
[2]
12
[3]
22
[4]
11
[5]
90
[6]
Current Position
Current Minimum
Comparing
Swapping
Sorted
Operation Logs
No operations yet
Algorithm Info
Time Complexity: O(n²) for all cases
Space Complexity: O(1) - in-place sorting
Stable: No - may change relative order of equal elements
How it works: Find the minimum element in unsorted portion and swap it with the first unsorted element. Repeat for each position.
Advantage: Performs fewer swaps than bubble sort (at most n-1 swaps).
Disadvantage: Always takes O(n²) time, even for sorted arrays.
Implementation
function selectionSort(arr) {
  const n = arr.length;
  
  for (let i = 0; i < n - 1; i++) {
    // Find minimum element in unsorted portion
    let minIdx = i;
    
    for (let j = i + 1; j < n; j++) {
      if (arr[j] < arr[minIdx]) {
        minIdx = j;
      }
    }
    
    // Swap minimum with current position
    if (minIdx !== i) {
      [arr[i], arr[minIdx]] = [arr[minIdx], arr[i]];
    }
  }
  
  return arr;
}