Coding Interview Prep: Algorithms - Implement Insertion Sort (freeCodeCamp)

 Implement Insertion Sort

The next sorting method we'll look at is insertion sort. This method works by building up a sorted array at the beginning of the list. It begins the sorted array with the first element. Then it inspects the next element and swaps it backwards into the sorted array until it is in sorted position. It continues iterating through the list and swapping new items backwards into the sorted portion until it reaches the end. This algorithm has quadratic time complexity in the average and worst cases.

Instructions: Write a function insertionSort which takes an array of integers as input and returns an array of these integers in sorted order from least to greatest.


Solution:


function insertionSort(array) {
  // Only change code below this line
  for(let i=1;i<array.length;i++) {
    let currItem = array[i]
    for(let j=i-1;j<array.length && array[j] > currItem;j--) {
      if(array[j] > array[j+1]) {
        let temp = array[j]
        array[j] = array[j+1]
        array[j+1] = temp 
      }
    }
  }
  console.log(array)
  return array;
  // Only change code above this line
}

insertionSort([1428345123433256436312343255123492]);

thedawnsoft-insertionsort


Click here to go to the original link of the question.

Post a Comment

Previous Post Next Post