Insertion Sort
InsertionSort(array, start, stop)
- for j = start+1 to stop
- key = array[j]
- i = j-1
- while i> 0 and array[i] > key
- array[i+1] = array[i]
- i--
- array[i+1] = key
This sort works by constantly increasing the size of the array that is in order
- At the first step, the array from start to start is sorted.
- After 1 iteration, start to start+1 is in order.
- After k iterations, start to start+k is in order.
- After n iterations, start to stop is in order
Consider the following example:
j i tmp array
- - 8 3 5 6 2 7 4
1 0 3 8 8 5 6 2 7 4
-1 3 3 8 5 6 2 7 4
2 1 5 3 8 8 6 2 7 4
0 5 3 5 8 6 2 7 4
3 2 6 3 5 8 8 7 2 4
1 6 3 5 6 8 7 2 4
4 3 7 3 5 6 8 8 2 4
2 7 3 5 6 7 8 2 4
5 4 2 3 5 6 7 8 8 4
3 2 3 5 6 7 7 8 4
2 2 3 5 6 6 7 8 4
1 2 3 5 5 6 7 8 4
0 2 3 3 5 6 7 8 4
-1 2 2 3 5 6 7 8 4
6 5 4 2 3 5 6 7 8 8
4 4 2 3 5 6 7 7 8
3 4 2 3 5 6 6 7 8
2 4 2 3 5 5 6 7 8
1 4 2 3 4 5 6 7 8
What is the performance of this sort?
- What is the best case?
- What is the worst case?
- What is the average case?
Do we believe that this sort is correct? IE will it sort things?
This is an in place sort
- It requires only constant additional space to perform the sort.
- This is good.
This is also a stable sort.
- If two elements have the same value, then their relative positions are preserved.
- This property will be valuable later.
This sort is good when we have a dynamic array
- We can insert the new item at the end of the dynamic array
- Then use 1 iteration of the sort to keep it in order.