Selection Sort Algorithm

A simple comparison-based sorting algorithm that selects the smallest element and places it in the sorted portion.

64
25
12
22
11
36
7
41
UnsortedCurrentMinimumSorted
1function selectionSort(arr) {
2  // Iterate through the array
3  for (let i = 0; i < arr.length - 1; i++) {
4    let minIndex = i;
5    
6    // Find the minimum element in the 
7    // unsorted part of the array
8    for (let j = i + 1; j < arr.length; j++) {
9      if (arr[j] < arr[minIndex]) {
10        minIndex = j;
11      }
12    }
13    
14    // Swap if the minimum element is not 
15    // at its sorted position
16    if (minIndex !== i) {
17      [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
18    }
19  }
20  
21  return arr;
22}