HWK 1
HWK 1
HWK 1
1
4. [Insertion Sort] Here is the C code for a sorting algorithm called insertion sort:
void insertionsort(int a[], int n) {
int i,j,v;
Roughly speaking, this algorithm works by sorting the rst i 1 elements, then inserting
the ith element where it belongs among the rst i 1. In this problem we'll consider
the number of comparisions between elements as our measure of the running time of
the algorithm. (This is the number of times the code v >= a[j] is executed.)
(a) If the initial array consists of n distinct elements in decreasing order, how many
comparisons are done? Justify your answer.
(b) If the initial array consists of n distinct elements in increasing (sorted) order, how
many comparisons are done? Justify your answer.
It turns out that if the array is \mostly" sorted then insertion sort also does well.
Call a pair of indices hi; j i an inversion in an array A = (a0; : : : ; an 1) if i < j but
ai > aj .
(c) Let C be the number of comparisons used to sort an array A. Let I be the number
of inversions in A. Prove that:
I C n 1+I
5. Attach a photo of yourself to your handin, or alternatively, write down the URL of a
photo of yourself. Students not solving problem 5 may be subjected to spontaneous
use of the instructor's digital camera at some point in the course.