50 likes | 123 Views
Explore the efficiency of various sorting algorithms in different input scenarios - sorted order, reversed order, nearly correct order. Understand how Bubble, Insertion, Selection, and Heap sort perform based on input type.
E N D
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) = (n3 lg n / 2n) = O(1) o(1) 1 • B(n) = n3 / lg n = (n3/lg n) 5 • C(n) = 1000 n lg n = (n lg n) 3 • D(n) = 5 n2 = (n2) 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 isO(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.
3 7 1 8 1 3 2 L 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 <= 2*p->next->data)) p->next = p->next->next; p = p->next; } } Let L be a pointer on the following linked list: 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: (n2) 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) • Bubble: (n2) n(n-1)/2 • Insertion: (n2) n(n-1)/2 • Selection: (n2) • 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: (n2) 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: (n2) n(n-1)/2 • Insertion: (n) 2n-3 • Selection: (n2) n(n-1)/2 • Heap: (n lg n) < 3n lg n