CS 367 - Introduction to Data Structures - Section 3

Written Assignment One: Sorting with Priority Queues
Solution

  1. Write C++ code (or pseudocode) for a sort function that uses priority queues and has the following interface:
    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.


  2. Explain what restrictions, if any, apply to the template parameter Item. (For example, does it require a copy constructor? Will it work for C++ builtin types? etc.)

    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.)



  3. 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 ).



  4. What would the run-time of your algorithm be if the complexity of the priority queue operations were as follows:
    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)).