Sorting Algorithms: Insertion Sort

Akiko Green
Nerd For Tech
Published in
4 min readFeb 10, 2023

--

cute coffee gif

Insertion Sort is a sorting algorithm that consumes an input element for each repetition and grows a sorted output. How this works is, at each iteration, the algorithm removes/ holds one element from the array, looks for the location it belongs to within the sorted list, and inserts that element back into the array at the correct sorted index.

Pseudocode

  • Start by picking the second element in the array.
  • Compare the second element with the element before i. Swap if that second element is greater than the one before i.
  • Continue to the next element, and if it is in the incorrect order, loop through the sorted portion, (the left side) to place that element in the current place.
  • Repeat till array is sorted.

The Code With Comments

function insertionSort(arr){
//start looping at first index
for(var i = 1; i < arr.length; i++){
//assign a plae holder varible at the index of i to keep track f the value we are looking at
var currentVal = arr[i]…

--

--

Akiko Green
Nerd For Tech

Software Engineer, Novice Blogger, Indoor Climbing Cutie 🥰