R

E

A

C

T

O

xamples 

epeat

ode

pproach

ptimize

est

{ Insertion Sort }

The Question

Can you implement the insertion sort algorithm?

Example

Given the array: [4, 2, 6, 2, 3]

The insertionSort function should return: [2, 2, 3, 4, 6]

Video of Insertion Sort

Algorithm in Words

Data is divided into sorted and unsorted portions.  One by one, the unsorted values are inserted into their appropriate positions in the sorted subarray

PseudoCode

Visual Representation

One Possible Solution

'use strict'
function insertionSort(arr){
    for(let i = 1; i < arr.length; i++){
        let j = i;
        while(arr[j-1] > arr[j] && j > 0){
            let temp = arr[j];
            arr[j] = arr[j-1];
            arr[j-1] = temp;
            j--;
        }
    }
    return arr;
}

Efficiency  

  • Time Efficiency in best case: O(n)
  • Time Efficiency in worst case: O(n^2)
  • Space Efficiency: O(1)

In the best case the array will already be sorted, but we have to look at each element to recognize that, thus O(n)

In the worst case the array will be reversed and we will have to touch each element n times, thus O(n^2)

The array is sorted in place, thus there is only constant O(1) additional space required

Interesting Fact: When people manually sort cards in bridge, they typically use a method similar to insertion sort

Solution

Insertion Sort

By pat310

Insertion Sort

Technical interview problem for implementing the insertion sort algorithm

  • 1,603