Midterm Review CS112 Fall 2003
Problem 1 You are a manager. You must implement some functionality. A number of your subordinates bring to you a number of proposed implementation methods. The corresponding performance characteristics are given below. –Order these in order of your preference, best choice first (assume your applications require very large n): A(n) = (n 3 lg n / 2 n ) = O(1) o(1)1 B(n) = n 3 / lg n = (n 3 /lg n)5 C(n) = 1000 n lg n = (n lg n)3 D(n) = 5 n 2 = (n 2 )4 E(n) = 100 n = (n)2 –One of the engineers advocates an algorithm for which he can only show that it is (lg n). What can you say about it as compared to the above? Definitely worse than A. All others can be either. –Another engineer advocates another algorithm for which he can only show that it is O(n2). What can you say about it as compared to those in a)? [do not confuse O and ] Definitely, better than B. All others can be either.
Problem 2 Assume that linked lists are implemented using the following declaration class ListNode {public: int data; ListNode * next; }; Consider the following function: void grow(ListNode * L) { p = L; while(p != NULL) { while((p->next!=NULL)&&(p->data next->data)) p->next = p->next->next; p = p->next; } Let L be a pointer on the following linked list: L p
Problem 3 How fast each of the following sorting algorithms work on the input of n elements given in –the correct sorted order (e.g. 1,2,3,4,5,6,7,8) Bubble: (n)n-1 Insertion: (n)n-1 Selection: (n 2 )n(n-1)/2 Heap: (n lg n)< 3n lg n –in the reversed sorted order (e.g. 8,7,6,5,4,3,2,1) 2Bubble: (n 2 )n(n-1)/2 2Insertion: (n 2 )n(n-1)/2 Selection: (n 2 ) Heap: (n lg n)
Problem 3 How fast each of the following sorting algorithms work on the input of n elements given in –in almost correct order: the largest element is in the first position, (e.g. 8,1,2,3,4,5,6,7) Bubble: (n)2n-3 Insertion: (n)2n-3 Selection: (n 2 )n(n-1)/2 Heap: (n lg n)< 3n lg n –as above, except the smallest element is in the last position, (e.g. 2,3,4,5,6,7,8,1) Bubble: (n 2 )n(n-1)/2 Insertion: (n)2n-3 Selection: (n 2 )n(n-1)/2 Heap: (n lg n)< 3n lg n