Insertion Sort Algorithm

How Insertion Sort Works?

Insertion sort loops over an array. At each iteration, we will insert the element at current index into the sub-array before it. The element should be inserted at the position where the element before is less or equal to it, and the element after is greater or equal to it. So after insertion, all elements before the current index will be sorted. After we go over the entire array, all elements are sorted.

Animated GIF of the Insertion Sort

insertion sorting example

Insertion Sort Runtime  and  Space Complexity

Worst-case performance: О(n2) (array sorted in reverse order)

Best-case performance: O(n) (array sorted in desired order)

Average performance: О(n2)

Space Complexity: О(n) total, O(1) auxiliary

Insertion Sort in Java

Insertion Sort in Python

Insertion Sort in PHP

Insertion Sort in Javascript