Insertion Sort in Action

Let’s apply Insertion Sort to the array [4, 2, 7, 1, 3].

We begin the first pass-through by inspecting the value at index 1. This happens to contain the value 2:

images/optimizing_for_optimistic_scenarios/insertion_sort_6.png

Step 1: We temporarily remove the 2 and keep it inside a variable called tempValue. We represent this value by shifting it above the rest of the array:

images/optimizing_for_optimistic_scenarios/insertion_sort_7.png

Step 2: We compare the 4 to the tempValue, which is 2:

images/optimizing_for_optimistic_scenarios/insertion_sort_8.png

Step 3: Because 4 is greater than 2, we shift the 4 to the ...

Get A Common-Sense Guide to Data Structures and Algorithms in JavaScript, Volume 1 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.