2
SOLUTION SET 3—DUE 2/13/2008
Solution.
Let’s run the insertion sort first:
First step:
4 compared with 7, inserted before.
1 comparison. List:
4,7
,3,8,1,5,4,2
Second Step:
3 compared with 4, inserted before.
1 comparison (2 total so far). List:
3,4,7
,8,1,5,4,2
Third Step:
8 compared with 3.
8 compared with 4.
8 compared with 7, inserted after.
3 comparisons (5 total so far).List:
3,4,7,8
,1,5,4,2
Fourth Step:
1 compared with 3, inserted before.
1 comparison (6 total so far). List:
1,3,4,7,8
,5,4,2
Fifth Step:
5 compared with 1.
5 compared with 3.
5 compared with 4.
5 compared with 7, inserted before
4 comparisons (10 total so far). List:
1,3,4,5,7,8
,4,2
Sixth Step:
4 compared with 1.
4 compared with 3
4 compared with 4, inserted before.
3 comparisons (13 total so far). List
1,3,4,4,5,7,8
,2
Seventh Step:
2 compared with 1.
2 compared with 3, inserted before.
2 comparisons (15 total so far). List sorted.
So, an insertion sort run takes 15 comparisons. Now let’s look at a binary search
for comparison.
First step:
4 compared with 7, inserted before.
1 comparison. List:
4,7
,3,8,1,5,4,2
Second Step:
3 compared with 4, inserted before.
1 comparison (2 total so far). List:
3,4,7
,8,1,5,4,2
Third Step:
8 compared with 4.
8 compared with 7, inserted after
2 comparisons (4 total so far). List:
3,4,7,8
,1,5,4,2
Fourth Step:
1 compared with 4.