Skip to content

Selection Sort

swap(arr, i, j)

1
2
3
const swap = (arr, i, j) => {
  [arr[i], arr[j]] = [arr[j], arr[i]];
};

selectionSort(arr)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const selectionSort = arr => {
  for (let i = 0; i < arr.length; i++) {
    let smallest = i;
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[smallest] > arr[j]) {
        smallest = j;
      }
    }
    if (i !== smallest) swap(arr, i, smallest);
  }
  return arr;
};