What is Insertion Sort?
Grow a sorted section by sliding each new value left into its correct place.
Type a tool name, format or task
Grow a sorted section by sliding each new value left into its correct place. Interactive step-by-step animation with JavaScript code, complexity and front-end use cases.
Loading animation...
Grow a sorted section by sliding each new value left into its correct place. Treat the first value as a sorted list of one. Take the next value and slide it left while the neighbour is bigger. Repeat until every value has been inserted. Time complexity: O(n²), O(n) when almost sorted. Space complexity: O(1). Fast on small or nearly sorted lists, which is why engines use it inside their built-in sort for short arrays.
Grow a sorted section by sliding each new value left into its correct place.
Time: O(n²), O(n) when almost sorted. Space: O(1).
Fast on small or nearly sorted lists, which is why engines use it inside their built-in sort for short arrays.
No. This converter runs in your browser for ordinary use, so the input is not sent to a backend by this tool.
Keep working without searching again.
The left part is treated as sorted. Each new value is slid left until it sits in the right place.
function insertionSort(arr) {for (let i = 1; i < arr.length; i++) {let j = i;while (j > 0 && arr[j - 1] > arr[j]) {[arr[j - 1], arr[j]] = [arr[j], arr[j - 1]];j--;}}return arr;}
Tip: use the arrow keys to step and the space bar to play or pause.