Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Member-only story

Sorting Algorithms: Insertion Sort

--

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]…

--

--

Nerd For Tech
Nerd For Tech

Published in Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Akiko Green
Akiko Green

Written by Akiko Green

Software Engineer, Novice Blogger, Indoor Climber and Dog sitting expert 🥰

No responses yet