Selection Sort

JavaScript Algorithm Walkthrough

Catherine Jimenez
1 min readJan 22, 2021

Selection sort sorts an array by locating the element with the smallest value and placing it at the beginning of the array.

let theFirst = [3, 4, 56, 43, 8, 99]function select(arr){
let swap = (array, i1, i2) => ([arr[i1], arr[i2]]= [arr[i2], arr[i1]])
let min
for(let i = 0; i < arr.length; i++){
min = i
for(let j = i + 1; j < arr.length; j++){
if(arr[j] < arr[min]){
min = j
}
}
if(i !== min){
swap(arr, i, min)
}
return arr
}
  1. Set up swap function to switch positions within the array.
let swap = (array, i1, i2) => ([arr[i1], arr[i2]]= [arr[i2], arr[i1]])

2. Create a variable for min (minimum value in array) before looping through the given array. When looping through the array, set min to i.

for(let i = 0; i < arr.length; i++){
min = i
}

3. Create nested loop that begins at the index after i. Create a conditional statement to check whether the value of array[j] is less than min. If so, reassign j as the new min.

for(let j = i + 1; j < arr.length; j++){
if(arr[j] < arr[min]){
min = j
}
}

4. Outside of the inner loop, check whether i was the original min. If min is no longer equal to i, switch positions within the array.

if(i !== min){
swap(arr, i, min)
}

5. Return sorted array outside of outer loop.

--

--

Catherine Jimenez

Latina Software Engineer | Ravenclaw rising | cat lady