Insertion sort is a sort-as-you-go method. You sort the elements are you walk through them. You “insert” the element into an already sorted list. This method is more complex to code. Click here for the Insertion Sort assignment.
Logic
Basic Logic
Choose an element to sort.
Assume all of the elements left of the element you are going to sort are already sorted.
Find where in the array to the left the element goes, place it there, and move all the other items to the right.
Repeat with the next element in the array.
Walkthrough Logic
Start with the second element in the array since the first element is already sorted with itself.
Compare the second element with the first element. If the second element is smaller (ascending order) than the first, swap the elements.
Look at the third element.
Compare it with the second. If it goes before the second, then compare it with the first to determine where it should fit.
Move the third element into the location where it should go and then move the other elements over.
Repeat
Coding
You will need two loops for this, but the inner loop will be different.
Outer loop
controls which element is being sorted.
starts at the second element because the first is sorted with itself.
needs to go to the last element because this algorithm is looking left, not right.
Inner loop
this loops sorts the element chosen in the outer loop with all the elements to the left
a while or do-while works better for this loop
keep looking left until you find an element that is smaller than the element to be sorted. Don’t go past zero.
The sorted element goes to the right (+1) of the element smaller or at position 0 if it is the smallest.
The shifting of items around can be done one of two ways,
Bubble sort the element to be sorted back to the left until it is where it needs to be.
Place the element to be sorted where it needs to be and run a for loop to shift everything to the right.