Insertion sort is one of the simplest sorting algorithms, it works the way we sort the playing cards. It iterates up the given array, and growing a sorted array behind. At each array-position, it checks the value there against the value in the previous array-position. If larger, it leaves the element in that position and moves to the next. If smaller, it inserts the element into the correct position, shifting the larger values up to make space.

Example illustrating Insertion sort:

Input : 21 9 3 12 6 21 9 3 12 6 9 21 3 12 6 // sorted subarray = {9,21} 3 9 21 12 6 // sorted subarray = {3,9,21} 3 9 12 21 6 // sorted subarray = {3,9,12,21} 3 6 9 12 21 output : 3 6 9 12 21

**Complexity**

Time complexity :O( N -- N² -- N² )[Best -- Average -- Worst] Memory :O(1)i.e. just the input array:"in place" Stable : Yes i.e. doesn't change relative order of elements with same key # N being the number of elements in the array

You can read about complexities of other sorting algorithms here.

**Usage**

It is much less efficient on larger arrays than the advanced sorting algorithms like **quicksort, merge sort **and** heapsort**. Easier to implement, more efficient in practice that the other O(N²) algorithms like **selection sort** and **bubble sort**.

**Bottom line: **Use this over selection or bubble sort.