Insertion Sort

Insertion Sort builds the sorted array one element at a time by inserting each element into its correct position. It's efficient for small datasets and nearly sorted arrays.

Insertion Sort Visualization

Complexity

Time Complexity: O(n²)
Space Complexity: O(1)

Pseudocode

function InsertionSort(array):
  for i from 1 to length(array)-1:
    key = array[i]
    j = i - 1
    
    while j >= 0 and array[j] > key:
      array[j+1] = array[j]
      j--
    
    array[j+1] = key