Description

  • Good for data sets that are partially sorted
  • Suitable for small data sets
Insertion Sort

Time & Space Complexity

  • Time:
    • Best: O(n)
    • Average: O(n^2)
    • Worst: O(n^2)
  • Space:
    • O(1)

Implementation

javascript

function insertionSort(array) {
  for(let i=1; i<array.length; i++) {
    // Value that is going to be sorted
    const key = array[i];
    // Index of comparing value
    let pointer = i;

    /** 
     * Stop looping if:
     * 1. pointer is less than 0 (finished searching)
     * 2. comparing value is smaller than key (found index to move to)
     */
    while(pointer >= 0 && array[pointer] > key) {
      // Move array element to right of their current index
      array[pointer + 1] = array[pointer]; 
      pointer--;
    }

    // Put the key at the sorted position
    array[pointer + 1] = key;
  }
}

More explanation on the above implementation here.

Possible Test Cases

javascript

const array1 = [] // Given array is empty
const array2 = [3] // Given array contains only a single element
const array3 = [0, 0, 0, 0] // Given array contains only zeros
const array4 = [2, 2, 2, 2] // Given array contains same elements
const array5 = [1, 2, 3, 4, 5] // Given array is already sorted
const array6 = [5, 4, 3, 2, 1] // Given array is reversed
const array7 = [-2, -5, 3, 1, 0] // Given array contain both positive and negative numbers
const array8 = generateRandom(10000) // Given array contains large number of elements

Working Example

Type yarn test on console to run vitest.

Practice Problems

  1. LeetCode 147