Data Structures and Algorithms: CHAPTER 8: Sorting
Fig. 8.5. Insertion sort.
Example 8.2. We show in Fig. 8.6 the initial list from Fig. 8.3, and the result of the passes of insertion sort for i = 2, 3, . . . , 6. After each pass, the elements above the line are guaranteed to be sorted relative to each other, although their order bears no relation to the records below the line, which will be inserted later.
Fig. 8.6. The passes of insertion sort.
Selection Sort
The idea behind "selection sorting" is also elementary. In the ith pass, we select the record with the lowest key, among A[i], . . . , A[n], and we swap it with A[i]. As a result, after i passes, the i lowest records will occupy A[1] , . . . , A[i], in sorted order. That is, selection sort can be described by
for i := 1 to n-1 do
select the smallest among A[i], . . . , A[n] and swap it with A[i];
A more complete program is shown in Fig. 8.7.
Example 8.3. The passes of selection sort on the list of Fig. 8.3 are shown in Fig. 8.8. For example, on pass 1, the ultimate value of lowindex is 4, the position of Agung, which is swapped with Pelee in A[1].
The lines in Fig. 8.8 indicate the point above which elements known to be smallest appear in sorted order. After n - 1 passes, record A[n], Vesuvius in Fig. 8.8, is also in its rightful place, since it is the element known not to be among the n - 1 smallest.
Time Complexity of the Methods
Bubblesort, insertion sort, and selection sort each take O(n2) time, and will take Ω(n2) time on some, in fact, on most input sequences of n elements. Consider