prep4place
Back to Visualizer

Selection Sort

Selection Sort is an in-place comparison sorting algorithm that divides the input into a sorted and unsorted region, repeatedly selecting the smallest element from the unsorted region.

Best: O(n²)Avg: O(n²)Space: O(1)
Size:20
Speed:50%
Default
Comparing
Swapping
Sorted
Pivot
Current
0
Comparisons
0
Swaps

How It Works

  1. 1Find the minimum element in the unsorted portion
  2. 2Swap it with the first unsorted element
  3. 3Move the boundary of sorted portion one step right
  4. 4Repeat until the entire array is sorted
  5. 5Each pass places one element in its final position

Time Complexity

Best CaseO(n²)
Average CaseO(n²)
Worst CaseO(n²)
Space ComplexityO(1)

Code

function selectionSort(arr) {
  const n = arr.length;
  
  for (let i = 0; i < n - 1; i++) {
    let minIdx = i;
    
    // Find minimum in unsorted portion
    for (let j = i + 1; j < n; j++) {
      if (arr[j] < arr[minIdx]) {
        minIdx = j;
      }
    }
    
    // Swap minimum with first unsorted
    if (minIdx !== i) {
      [arr[i], arr[minIdx]] = [arr[minIdx], arr[i]];
    }
  }
  
  return arr;
}