template <class Item> void pqSort(Item A[], size_t n); // Precondition: The number of items in // array A is given by n. // Postcondition: A is now sorted in // decreasing order.C++ code implementing pqSort can be found here.
The template parameter Item is the data type of the items in the array - it is also the data type of both the items and the keys in the priority queue. Thus, Item may be any C++ built-in type that has a comparison operator (<), or a class with a copy constructor, assignment operator, destructor, equality(==), inequality(!=), and comparison(<). (Notice that these are the same restrictions mentioned in the priority queue header files.)
Give big-O analysis for your sort function.
The run-time complexity of the function is O(n2 ). The analysis is as follows: the function consists of two for loops. The first for loop iterates n times, each time calling insert which is O(1), so the first for loop takes a total of O(n) time. The second for loop also iterates n times, each time calling extractMax which is O(n) in the worst case. So, the second loop is O(n2 ) in the worst case. Therefore, the worst-case running-time complexity of pqSort is O(n + n2 ) = O(n2 ).
insert - O(lg n) maximum - O(1) extractMax - O(lg n)
The run-time complexity of pqSort in this case is O(n*lg(n)). The analysis is as follows: the function consists of two for loops. The first for loop iterates n times, each time calling insert which is O(lg(n)), so the first for loop takes a total of O(n*lg(n)) time. The second for loop also iterates n times, each time calling extractMax which is O(lg(n)) in the worst case. So, the second loop is also O(n*lg(n)) in the worst case. Therefore, the worst-case running-time complexity of pqSort is O(n*lg(n) + n*lg(n)) = O(n*lg(n)).