← Back

Insertion Sort

comparisonin-placestableadaptive
Press play to start
1function insertionSort(arr: number[]): number[] {
2 for (let i = 1; i < arr.length; i++) {
3 const key = arr[i]
4 let j = i - 1
5 while (j >= 0 && arr[j] > key) {
6 arr[j + 1] = arr[j]
7 j--
8 }
9 arr[j + 1] = key
10 }
11 return arr
12}
Step 1/0
Custom array:

Complexity

Best:O(n)
Average:O(n²)
Worst:O(n²)
Space:O(1)

Description

Builds the sorted array one element at a time by inserting each new element into its correct position within the already-sorted portion.

When to use

Excellent for small arrays or nearly-sorted data. Used as a subroutine in more complex algorithms like Timsort.