What is Insertion Sort?

Insertion Sort is a simple comparison-based sorting algorithm that sorts an array by iteratively building a sorted sublist from the unsorted portion of the input array. It is best suited for small arrays or arrays that are already partially sorted.

Time and Space Complexity

Time Complexity:

Space Complexity:

How does it work?

Insertion Sort divides the given array into two parts - sorted and unsorted

For the unsorted part, take the first element and place it at the correct position in the sorted array. Shove all the elements which are larger than 1st element by one position.

Screenshot 2023-04-12 at 5.49.12 PM.png

Example

Screenshot 2023-04-12 at 5.34.54 PM.png

  1. pick the first element (which is 3) and that is considered the “sorted” side

  2. The actual algo starts in the second element

    Screenshot 2023-04-12 at 5.38.52 PM.png

  3. You first create a temp variable which holds the value of the current unsorted element you are trying to sort. This will create an “empty” space in the array

    Screenshot 2023-04-12 at 5.41.38 PM.png