Skip to content

ts-ds / insertionSort

Function: insertionSort() ​

ts
function insertionSort<T>(array, compareFn?): void;

Defined in: sort/insertion/insertion.ts:18

Sorts an array in place using insertion sort.

Keeps the prefix array[0..i-1] sorted and inserts array[i] into it, shifting greater elements one position to the right. Fast on small and nearly sorted arrays.

Time: bestTime: averageTime: worstMemoryStableIn place
O(n)O(n²)O(n²)O(1)yesyes

Type Parameters ​

Type ParameterDescription
T

Parameters ​

ParameterTypeDefault valueDescription
arrayT[]undefinedArray to sort. It is modified.
compareFn?CompareFn<T>defaultCompareOrder of elements, ascending by default.

Returns ​

void

Nothing — array itself is sorted.

MIT License