Insertion Sort
One of the simplest methods to sort an array is an insertion sort. An example of an insertion sort occurs in everyday life while playing cards. To sort the cards in your hand you extract a card, shift the remaining cards, and then insert the extracted card in the correct place. This process is repeated until all the cards are in the correct sequence. Both average and worst-case time is O(n2). For further reading, consult Knuth [1998].
Theory
Starting near the top of the array in Figure 2-1(a), we extract the 3. Then the above elements are shifted down until we find the correct place to insert the 3. This process repeats in Figure 2-1(b) with the next number. Finally, in Figure 2-1(c), we complete the sort by inserting 2 in the correct place.
Figure 2-1: Insertion Sort
Assuming there are n elements in the array, we must index through n- 1 entries. For each entry, we may need to examine and shift up to n- 1 other entries, resulting in a O(n2) algorithm. The insertion sort is an in-place sort. That is, we sort the array in-place. No extra memory is required. The insertion sort is also a stable sort. Stable sorts retain the original ordering of keys when identical keys are present in the input data.
Implementation in C
An ANSI-C implementation for insertion sort is included. Typedef
T
and comparison operator compGT
should be altered to reflect the data
stored in the table.
Implementation in Visual Basic
A Visual Basic implementation for insertion sort is included.