Instructor: To create our insertion sort algorithm, we'll create a function accepts an array, sorts it, and then returns it. Insertion sort works by using a nested loop. We'll take the first item in the list and assume we have a sorted list of length one. We'll then compare the next item to it and place it before or after it depending on which item is greater.
Since we'll have two loops going, we need to create two iteration variables. We'll use I and J. Next, our outer loop will start at the second element in the array, thus I will start at the value of one. This loop will loop through the entire length of the array from the second item. We can use I is less than array.length, and we can increment I.
We'll have an inner loop that starts at the first item in our list, so J will start at zero. We only want to loop up to the current item being iterated over in our outer loop, so our second statement in this is J is less than I. Here, we want to increment J.
Remember, this inner loop will reset each time our outer loop advances to the next number. What we want to do inside our two loops is compare the item at array index I to array index J. If item I is less than item J, then we want to move the item I to the position of item J.
I'm going to use array destructuring to get an item variable. I'm going to use the splice method to get it. We want to splice at the index of I. We want to only get one item deleted and given back to us. I'm going to use the splice method again to insert that item at the J position.
That's the insertion sort algorithm, but we want to be able to visualize it. I'm going to use the print array utility method I've brought into the file in order to print each time we make a comparison. I want to add one more print array before we return the array.
This way, we'll get to see the array in its final sorted form. Now that I have that, I can create an array of unsorted numbers and pass those numbers to our insertion sort function. If I save that and print that to the terminal, we can examine how the algorithm worked through each iteration.
If we scroll up, we could see how 10 moved one spot during the first one, a few more spots each time afterwards. What this reveals to us is how the inner loop of J was comparing more numbers each time I got a little bit bigger. Eventually, we could see 10's moved all the way to the right and that our list is sorted and organized.