Answer
a) This is essentially the same as Algorithm 5, but working from the other end. However, we can do the
moving while we do the searching for the correct insertion spot, so the pseudocode has only one section.
procedure backward insertion sort(a1, a2, . . . , an : real numbers with n ≥ 2)
for j := 2 to n
m := aj
i := j − 1
while (m < ai and i > 0)
ai+1 := ai
i := i − 1
ai+1 := m
{ a1, a2, . . . , an are sorted}
b) On the first pass the 2 is compared to the 3 and found to be less, so the 3 moves to the right. We have
reached the beginning of the list, so the loop terminates (i = 0), and the 2 is inserted, yielding 2, 3, 4, 5, 1, 6.
On the second pass the 4 is compared to the 3, and since 4 > 3, the while loop terminates and nothing
changes. Similarly, no changes are made as the 5 is inserted. One the fourth pass, the 1 is compared all the
way to the front of the list, with each element moving toward the back of the list as the comparisons go on,
and finally the 1 is inserted in its correct position, yielding 1, 2, 3, 4, 5, 6. The final pass produces no change.
c) Only one comparison is used during each pass, since the condition m < ai is immediately false. Therefore
a total of n − 1 comparisons are used.
d) The jth pass requires j − 1 comparisons of elements, so the total number of comparisons is 1 + 2 + · · · +
(n − 1) = n(n − 1)/2.
Work Step by Step
a) This is essentially the same as Algorithm 5, but working from the other end. However, we can do the
moving while we do the searching for the correct insertion spot, so the pseudocode has only one section.
procedure backward insertion sort(a1, a2, . . . , an : real numbers with n ≥ 2)
for j := 2 to n
m := aj
i := j − 1
while (m < ai and i > 0)
ai+1 := ai
i := i − 1
ai+1 := m
{ a1, a2, . . . , an are sorted}
b) On the first pass the 2 is compared to the 3 and found to be less, so the 3 moves to the right. We have
reached the beginning of the list, so the loop terminates (i = 0), and the 2 is inserted, yielding 2, 3, 4, 5, 1, 6.
On the second pass the 4 is compared to the 3, and since 4 > 3, the while loop terminates and nothing
changes. Similarly, no changes are made as the 5 is inserted. One the fourth pass, the 1 is compared all the
way to the front of the list, with each element moving toward the back of the list as the comparisons go on,
and finally the 1 is inserted in its correct position, yielding 1, 2, 3, 4, 5, 6. The final pass produces no change.
c) Only one comparison is used during each pass, since the condition m < ai is immediately false. Therefore
a total of n − 1 comparisons are used.
d) The jth pass requires j − 1 comparisons of elements, so the total number of comparisons is 1 + 2 + · · · +
(n − 1) = n(n − 1)/2.