2016-12-14 InsertionSort

posted Dec 14, 2016, 7:01 AM by Samuel Konstantinovich   [ updated Dec 14, 2016, 7:01 AM ]

Goal Insertion Sort *You already wrote this but didn't realize!)


Insertion into a sorted list:

Consider you have a sorted list of elements. In order to add a new element, you must find where the element must go, and shift the elements over to make room:

I want to insert 5 into the list: 1,3,4,7,8,10

I look through the list and find that I must place 5 where the 7 is.

I move 7, 8, 10 over and place the 5 in the hole

1,3,4,5,7,8,10

This is an O(n) operation. It is considered to be a single insertion operation.


Insertion Sort:

Consider an array where the 1st half is sorted, and the rest is not:

[1,2,4,6, 3,10,0,5]

We can insert the 3 into the sorted portion of the array by pushing it back into the correct position:

3 < 6 so we move it back.

[1, 2, 4, 3, 6,10,0,5]

3 < 4 so we move it back again.

[1, 2, 3, 4, 6,10, 0, 5]

Since 3 > 2, we stop now.

We can then repeat this process for the 10, 0, and 5. This is called the insertion sort.


IMPORTANT Note: 

We don't want to swap each step of the way. If we wanted to move the current element back 100 places, it is better to just shift the numbers over and only at the end should we place the value in the correct spot. 

So to push back: 

-Pull out the number (into a temporary variable)

-Shift over all of the larger numbers

-Put back the number (from the temporary variable)


Can we use this on ANY list?

We can always consider that a single element is sorted, so we just say the 1st element is the sorted sublist, and the rest of the elements need to be pushed back into it:

[9, 10, 4, 3, 0 , 2] //9 is a single element sub-list that is sorted!


Final Example:

Using the insertion sort on the sequence {3, 7, 4, 9, 5, 2, 6, 1}. 

In each step, the key under consideration is underlined. 

The key that was moved (or left in place because it was biggest yet considered) in the previous step is shown in bold.

3 7 4 9 5 2 6 1

3 7 4 9 5 2 6 1

7 4 9 5 2 6 1

4 7 9 5 2 6 1

3 4 7 9 5 2 6 1

3 4 5 7 9 2 6 1

2 3 4 5 7 9 6 1

2 3 4 5 6 7 9 1

1 2 3 4 5 6 7 9

Comments