1. Exercise 2.2-1
Question:Express the function n^3 /1000-100n^2-100n+3 in terms of Θ-notation.
Answer: Θ(n^3)
2. Exercise 2.2-2
Question: Consider sorting n numbers stored in array A by first finding the smallest element of A and exchanging it with the element in A[1]. Then find the second smallest
element of A, and exchange it with A[2]. Continue in this manner for the first n-1 elements of A. Write pseudocode for this algorithm, which is known as selection sort. What loop invariant does this algorithm maintain? Why does it need to run for only the first n-1 elements, rather than for all n elements? Give the best-case and worst-case running times of selection sort in Θ-notation.
Answer:
Source code:
void selectionSort(int *a, int len)
{
int i, j, min, index, temp;
for(i = 0; i < len - 1; i++){
min = a[i];
index = 0;
for(j = i + 1; j < len; j++){
if(a[j] < min){
min = a[j];
index = j;
}
}
if(index != 0){
temp = a[i];
a[i] = a[index];
a[index] = temp;
}
}
}
Loop invariant: 在第4~18行的for循环的每次迭代开始时,子数组a[0...i-1]由比子数组a[i...n-1]中任意元素小的元素组成,并已排好序。
It needs to run for only the first n-1 elements, rather than for all n elements, just because loop invariant determines it.
The best-case running times of selection sort: Θ(n^2).
The worst-case running times of selection sort : Θ(n^2).
3. Exercise 2.2-3
Question:Consider linear search again (see Exercise 2.1-3). How many elements of the input sequence need to be checked on the average, assuming that the element being
searched for is equally likely to be any element in the array? How about in the worst case? What are the average-case and worst-case running times of linear search in Θ-notation? Justify your answers.
Answer:
Source code
void linearSearch(int *a, int len, int v)
{
int i, flag;
flag = 0;
for(i = 0; i < len; i++){
if(a[i] == v){
flag = 1;
printf("a[%d] == %d\n", i, v);
}
}
if(flag == 0)
printf("%d does not exist in this array.\n", v);
}
Half the elements of the input sequence need to be checked on the average.
The average-case and worst-case running times of linear search is Θ(n).