Insertion Sort
Insertion Sort is a stable comparison sort algorithm with poor performance. Insertion Sort uses the insertion method and while it can perform at O(n) in the best case, it performs at O(n2) in the average and worst case.
Table of contents
Performance
TIP — When you share this page, the preview image generated displays the algorithm's Big-O runtime!
Code
Walkthrough
Insertion Sort consists of a while-loop nested in a for-loop. The algorithm executes in the following steps:
- Loop through every value of the array starting with the first index. This is because we will be comparing each index with the previous index.
- Save the current index of the for-loop to a variable named
currentIndex
. - Start the while-loop and check these 2 conditions:
- That the
currentIndex
is at least 1 - That the value at the previous index is greater than the value at
currentIndex
- That the
- If the above conditions are true, swap the values at the
currentIndex
and previous index. - Decrement the
currentIndex
and go back to the start of the while-loop.