JS Built-ins
Algorithmsintermediate

Insertion Sort

πŸ“– Usage Example
function insertionSort(arr) {
  const a = [...arr];
  for (let i = 1; i < a.length; i++) {
    const key = a[i]; let j = i - 1;
    while (j >= 0 && a[j] > key) { a[j+1] = a[j]; j--; }
    a[j+1] = key;
  }
  return a;
}

Insertion sort builds the sorted array one element at a time by shifting larger values.

Insertion Sort

Insertion Sort builds the sorted array one item at a time. It iterates through the array, and for each element, finds the correct position in the sorted portion and inserts it there.

Time Complexity: O(nΒ²) worst case, O(n) best case Space Complexity: O(1)

function insertionSort(arr: number[]): number[] {
  // Implement insertion sort
  // Insert each element into its correct position
}

insertionSort([64, 34, 25, 12, 22]) // [12, 22, 25, 34, 64]
πŸ’‘ Hints (3)
  • β€’ Start from index 1 and build the sorted portion from left to right.
  • β€’ For each element, shift larger elements to the right until you find the correct position.
  • β€’ Use a while loop to find the insertion point.