A-level Computing 2009/AQA/Problem Solving, Programming, Operating Systems, Databases and Networking/Programming Concepts/Insertion sort





You should have covered bubble sort during the AS course. Unfortunately bubble sort is a very slow way of sorting data and very rarely used in industry. We'll now look at a much faster algorithm, insertion sort.

Insertion sort is a simple sorting algorithm: a comparison sort in which the sorted array (or list) is built one entry at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort and you may cover these at university. However, insertion sort provides several advantages:
 * simple implementation
 * efficient on small data sets
 * uses a fixed amount of memory when running

Insertion sort requires the use of two arrays, one ordered, and one unordered. Each repetition of the algorithm moves an item from the unordered list, into a sorted position in the ordered list, until there are no elements left in the unordered list.

Sorting is typically done in-place without needing extra memory. The resulting array after k iterations has the property where the first k + 1 entries are sorted. In each iteration the first remaining entry of the input is removed, inserted into the result at the correct position, thus extending the result:



becomes



with each element greater than x copied to the right as it is compared against x.



The following table shows the steps for sorting the sequence {5, 7, 0, 3, 4, 2, 6, 1}. For each iteration, the number of positions the inserted element has moved is shown in parentheses. Altogether this amounts to 17 steps.

5	7	0	3	4	2	6	1	 	     (0)

5	7	 0 	3	4	2	6	1	 	     (0)

0	5	7	 3 	4	2	6	1	 	     (2)

0	3	5	7	 4 	2	6	1	 	     (2)

0	3	4	5	7	 2 	6	1	 	     (2)

0	2	3	4	5	7	 6 	1	 	     (4)

0	2	3	4	5	6	7	 1 	 	     (1)

0	1	2	3	4	5	6	7	 	     (6)

Insertion sort is a simple sorting algorithm: a comparison sort in which the sorted array (or list) is built one entry at a time.

sort left hand side is underlined 9 6 7 1 2 6 9 7 1 2 6 7 9 1 2 1 6 7 9 2 1 2 6 7 9

Show how the insert sort would work on the following unordered array

G K L A J

sort left hand side is underlined G K L A J G K L A J G K L A J A G K L J A G J K L