Docstoc

Data Structures Course Title Data

Document Sample
Data Structures Course Title Data Powered By Docstoc
					Course Title: Data Structures

Credits: 3:0

Course Designers:

1. S. Geetha Sgeetha@tce.edu
2. S. Sudha ssj@tce.edu
3. M.K. Kavitha Devi mkkdit@tce.edu
Background:

Program Outcomes addressed

a.   An   ability     to   apply     knowledge     of    engineering,        information    technology,
      mathematics, and science
c. An ability to design a system or component, or process to meet stated
     specifications
d. An ability to identify, formulate and solve engineering problems
Competencies
1. Ability to identify and implement appropriate data structure for a given
     application
2. Comprehend the terms "data abstraction", "abstract data type", and "data
     structures", and how data structures and algorithms have to be blended carefully
     to obtain efficient implementations.
3. Explain the notion of time complexity and the asymptotic notions of "Big Oh" with
     non-trivial examples.

4. Explain the difference between worst case complexity and best case complexity.
     Justify with an example algorithm for each of the complexities: O(n), O(n*2),
     O(n*3), O(2**n), O(n log n), O(n*2 log n),O(log n), O(log log n), O(sqrt(n)).

5. Identify all the trade-offs involved in choosing static versus dynamic data
     structures
6. In     the       context     of    searching,    identify        the   trade-offs       involved     in
     selecting the most efficient data structure.

7. In     the       context     of     sorting,    identify     the       trade-offs       involved     in
     selecting:      (a)      bubble-sort    (b)        insertion     sort      (c)    selection      sort
     (d) quick sort (e) merge sort (f) heap sort.




Formative and Summative Evaluation
                  Bloom’s Category    Test 1    Test 2   End-semester
                                                         examination
              1   Recall              30        20       10
              2   Comprehension       30        20       10
              3   Application         20        30       30
              4   Analysis            10        20       20
              5   Synthesis           0         0        0
              6   Evaluation          10        10       30


Course Level Learning Objectives:
Recall
1. What is data structure?

2. List out the areas in which data structures are applied extensively?

3. What are the major data structures used in the following areas: RDBMS, Network
   data model and Hierarchical data model?

4. What are the notations used in Evaluation of Arithmetic Expressions using prefix
   and postfix forms?

5. List out few of the applications of tree data-structure?

6. List out few of the applications that make use of Multilinked Structures?

7. What is the bucket size, when the overlapping and collision occur at same time?

8. What are the Collision Resolution Techniques and the methods used in each of
   the type?
9.

Comprehension

1. If you are using C language to implement the heterogeneous linked list, what
   pointer type will you use?

2. What is the minimum number of queues needed to implement the priority queue?

3. What is the data structure used to perform recursion?

4. How many null branches are there in a binary tree with 20 nodes?

5. What are the methods available in storing sequential files?

6. How many different trees are possible with 10 nodes?
7. What is the condition for balancing to be done in an AVL tree?

8. What is the type of the algorithm used in solving the 8 Queens problem?

9. How do you traverse a given tree using Inorder, Preorder and Postorder
   traversals.

10. What is the suitable efficient data structure for constructing a tree?

11. There are 8, 15, 13, 14 nodes were there in 4 different trees. Which of them
   could have formed a full binary tree?

12. At   what location can you store the node 4 in a given binary tree using array?




13. Sort the given values using Quick Sort?


                         65   70   75   80   85    60   55   50   45

14. Classify the Hashing Functions based on the methods by which the key value is
   found.
15. What is the efficient data structure used in the internal storage representation in
   RDBM?
16. What are the steps to inserting a new item at the head of a linked list? Use one
   short English sentence for each step.
17. Suppose that p is a reference to an IntNode in a linked list, and it is not the tail
   node. What are the steps to removing the node after p? Use one short English
   sentence for each step.
18. Give one of the Sequence operations that is more efficient because the class
   keeps a tail reference as a private instance variable. Provide a specific example
   showing why the operation would be less efficient without the tail reference.
19. Give one of the Sequence operations that is easier to program because the class
   keeps a precursor (rather than just a cursor). Provide a specific example showing
   why the operation would be harder to program without the precursor.
20. Write a class definition that could be used to define a node in a doubly linked list.
   Include only the instance variables, not the methods. Also write one sentence to
   describe a situation when a doubly linked list is appropriate.
21. Describe a situation where storing items in an array is clearly better than storing
   items on a linked list.
22. Suppose cursor refers to a node in a linked list (using the IntNode class with
   instance variables called data and link). What statement changes cursor so that it
   refers to the next node?
           A. cursor++;
           B. cursor = link;
           C. cursor += link;
           D. cursor = cursor.link;
23. Suppose cursor refers to a node in a linked list (using the Node class with
   instance variables called data and link). What boolean expression will be true
   when cursor refers to the tail node of the list?
           A. (cursor == null)
           B. (cursor.link == null)
           C. (cursor.data == null)
           D. (cursor.data == 0.0)
           E. None of the above.
24. Which boolean expression indicates whether the numbers in two nodes (p and q)
   are the same. Assume that neither p nor q is null.
           A. p == q
           B. p.data == q.data
           C. p.link == q.link
           D. None of the above.
25. Suppose that p is a reference variable that contains the null reference. What
   happens at runtime if the program tries to activate a method of p?
           A. IllegalArgumentException
           B. IllegalStateException
           C. NullPointerException
           D. The results are unpredictable.
26. Suppose that a method has one node as a parameter and it returns two
   references to nodes. What's the best header for the method?
           A. IntNode foo(IntNode p)
           B. IntNode, IntNode foo(IntNode p)
          C. IntNode[ ] foo(IntNode p)
          D. void foo(IntNode p, IntNode answer1, IntNode answer2)
27. Suppose that the Bag is implemented with a linked list. Which of these
   operations are likely to have a constant worst-case time?
          A. add
          B. countOccurrences
          C. remove
          D. None of (A), (B), and (C) have a constant worst-case time
          E. TWO of (A), (B), and (C) have a constant worst-case time
          F. ALL of (A), (B), and (C) have a constant worst-case time
28. Explain what modifications would be needed to make the parenthesis matching
   algorithm check expressions with more kinds of parentheses such as <>.
Application

1. Convert the expression ((A + B) * C - (D - E) ^ (F + G)) to equivalent Prefix and
   Postfix notations.

2. Draw the B-tree of order 3 created by inserting the following data arriving in
   sequence - 92 24 6 7 11 8 22 4 5 16 19 20 78

3. Draw a binary Tree for the expression : A * B - (C + D) * (P / Q)

4. Is a Linked List a linear or non-linear data structure?

5. Suppose we are using the usual IntNode class (with instance variables called
   data and link). Your program is using an IntNode variable called head to refer to
   the first node of a linked list (or head is null for the empty list). Write a few lines
   of C++ code that will print all the double numbers on the list?

6. Suppose we are using the usual IntNode class (with instance variables called
   data and link), and that locate is referring to a node in a linked list. Write an
   assignment statement that will make locate refer to the next node in the list (if
   there is one). If there is no next node, then your assignment statement should
   set locate to null.

7. Suppose that p, q, and r are all references to nodes in a linked list with 15 nodes.
   The variable p refers to the first node, q refers to the 8th node, and r refers to
   the last node. Write a few lines of code that will make a new copy of the list.
   Your code should set THREE new variables called x, y, and z so that: x refers to
   the first node of the copy, y refers to the 8th node of the copy, and z refers to
   the last node of the copy. Your code may NOT contain any loops, but it can use
   the other IntNode methods.

8. Suppose that a and b are IntNode variables. Write one clear sentence to when
   the expression (a==b) is true?

9. What is the output of these statements, using your Sequence ADT implemented
   as a linked list:
   a. DoubleLinkedSeq x = new DoubleLinkedSeq( );
   b. DoubleLinkedSeq y = new DoubleLinkedSeq( );
   c. x.addBefore(41); // Inserts 41 into the list x
   d. x.addBefore(42); // Inserts 42, so that x is now 42, 41 with cursor at front
   e. y = (DoubleLinkedSeq) x.clone( );
   f.   x.addAfter(43); // Attaches 43 so that x is now 42, 43, 41 with cursor at 43
   g. y.advance( );
   h. System.out.println("y size is " + y.size( ));
10. What is the expression for generating a pseudorandom number in the range
   1...N?
   a. (int) (Math.random() * N);
   b. (int) (Math.random() / N);
   c. (int) (Math.random() * (N + 1));
   d. (int) (Math.random() / (N + 1));
   e. (int) (Math.random() * N) + 1;
11. Which expression computes a pseudorandom integer between -10 and 10 using
   rand() from stdlib.h?
   a. (int) (Math.random( ) * 20) – 10
   b. (int) (Math.random( ) * 21) – 10
   c. (int) (Math.random( ) * 22) – 10
   d. (int) (Math.random( ) * 20) – 11
   e. (int) (Math.random( ) * 21) - 11
Evaluation

1. Compare the worst-case big-O time analysis for these two methods: The add
   method for the Bag that is implemented using an array, and the add method for
   the Bag that is implemented using a linked list.
2. Compare the worst-case big-O time analysis for these two methods: The remove
   method for the Bag that is implemented using a fixed-sized array, and the
   remove method for the Bag that is implemented using a linked list.
3. Compare the worst-case big-O time analysis for these two methods: The
   addBefore method for the Sequence that is implemented using an array, and the
   addBefore method for the Sequence that is implemented using a linked list.
4. Compare the worst-case big-O time analysis for these two methods: The remove
   method for the Sequence that is implemented using an array, and the remove
   method for the Sequence that is implemented using a linked list.




   1. Complete the body of this method. You do not need to check the precondition.
      You may use the CharStack class.

    public static boolean balanced(String p)
    // Precondition: Each character of p is '(', ')', '{' or '}'.
    // Postcondition: The method returns true if the characters form a
    // sequence of correctly balanced parentheses with each '(' matching
    // a ')' and each '{' matching a '}'. Note that a sequence such as
    // ( { ) } is NOT balanced because when we draw lines to match the
    // parentheses to their partners, the lines cross each other. On the
    // other hand, ( { } ) and { ( ) } are both balanced.
   I am going to execute this code with THREE pushes and ONE pop:
    IntStack s = new IntStack( );
    s.push(1);
    s.push(2);
    s.push(3);
    System.out.println(s.pop( ));

   Suppose that s is represented by a partially filled array. Draw the state of the private
   instance variables of s after the above code:

       _______ __________________________________
       manyItems| | data| | | | | |
       |_______| |______|______|______|______|______|...
       [0] [1] [2] [3] [4]
I am going to execute this code with THREE pushes and ONE pop:

IntStack s = new IntStack( );
s.push(1);
s.push(2);
s.push(3);
System.out.println(s.pop( ));

   Suppose that s is represented by a linked list. Draw the state of the private
   member variables of s after the above code:

   _______
    head| |
    |_______|

2. Implement the following method. You may use the IntStack class and the
   Stack operations of push, pop, peek, isEmpty, and size. The parameter, in, is
   an EasyReader from Appendix B of the text and it is already attached to some
   kind of input. You may use the methods:
      o in.isEOLN() -- returns true when the end of line is reached.
      o in.peek() -- returns the next input character without actually reading
          it.
      o in.ignore() -- reads and throws away the next input character.
      o in.intInput() -- reads and returns an integer value from the
          EasyReader. This should be used only if you know that the next input
          characters form a valid integer value.

   The method specification is:

    public static int evaluatePostfix(EasyReader in)
    // Precondition (Which is not checked): The next input line of in is a
    // properly formed postfix expression consisting of integers,
    // the binary operations + and -, and spaces.
    // Postcondition: The method has read the next input line (including
    // the newline) and returned the value of the postfix expression.
3. Consider the usual algorithm to convert an infix expression to a postfix
   expression. Suppose that you have read 10 input characters during a
   conversion and that the stack now contains these symbols:
||
|+|
|(|
bottom |___*___|

   Now, suppose that you read and process the 11th symbol of the input. Draw
   the stack for the case where the 11th symbol is:

       A. A number:
       B. A left parenthesis:
       C. A right parenthesis:
       D. A minus sign:
       E. A division sign:
Multiple Choice

   1. Entries in a stack are "ordered". What is the meaning of this statement?

          A. A collection of Stacks can be sorted.
          B. Stack entries may be compared with the '<' operation.
          C. The entries must be stored in a linked list.
          D. There is a first entry, a second entry, and so on.

   2. The operation for adding an entry to a stack is traditionally called:

          A. add
          B. append
          C. insert
          D. push

   3. The operation for removing an entry from a stack is traditionally called:

          A. delete
          B. peek
          C. pop
          D. remove

   4. Which of the following stack operations could result in stack underflow?

          A. is_empty
          B. pop
          C. push
          D. Two or more of the above answers

   5. Which of the following applications may use a stack?

          A. A parentheses balancing program.
          B. Keeping track of local variables at run time.
          C. Syntax analyzer for a compiler.
          D. All of the above.

   6. Consider the following pseudocode:

   declare a stack of characters
   while ( there are more characters in the word to read )
   {
   read a character
   push the character on the stack
   }
   while ( the stack is not empty )
   {
   pop a character off the stack
   write the character to the screen
   }

      What is written to the screen for the input "carpets"?
       A. serc
       B. carpets
       C. steprac
       D. ccaarrppeettss

7. Here is an INCORRECT pseudocode for the algorithm which is supposed to
   determine whether a sequence of parentheses is balanced:

declare a character stack
 while ( more input is available)
 {
 read a character
 if ( the character is a '(' )
 push it on the stack
 else if ( the character is a ')' and the stack is not empty )
 pop a character off the stack
 else
 print "unbalanced" and exit
 }
 print "balanced"

   Which of these unbalanced sequences does the above code think is balanced?

       A. ((())
       B. ())(()
       C. (()()))
       D. (()))()

8. Consider the usual algorithm for determining whether a sequence of
   parentheses is balanced. What is the maximum number of parentheses that
   will appear on the stack AT ANY ONE TIME when the algorithm analyzes:
   (()(())(()))?

       A. 1
       B. 2
       C. 3
       D. 4
       E. 5 or more

9. Consider the usual algorithm for determining whether a sequence of
   parentheses is balanced. Suppose that you run the algorithm on a sequence
   that contains 2 left parentheses and 3 right parentheses (in some order).
   What is the maximum number of parentheses that will ever appear on the
   stack AT ONE TIME during the computation?

       A. 1
       B. 2
       C. 3
       D. 4
       E. 5 or more
10. Suppose we have an array implementation of the stack class, with ten items
    in the stack stored at data[0] through data[9]. The CAPACITY is 42. Where
    does the push method place the new entry in the array?

       A. data[0]
       B. data[1]
       C. data[9]
       D. data[10]

11. Consider the implementation of the Stack using a partially-filled array. What
    goes wrong if we try to store the top of the Stack at location [0] and the
    bottom of the Stack at the last used position of the array?

       A. Both peek and pop would require linear time.
       B. Both push and pop would require linear time.
       C. The Stack could not be used to check balanced parentheses.
       D. The Stack could not be used to evaluate postfix expressions.

12. In the linked list implementation of the stack class, where does the push
    method place the new entry on the linked list?

       A. At the head
       B. At the tail
       C. After all other entries that are greater than the new entry.
       D. After all other entries that are smaller than the new entry.

13. In the array version of the Stack class, which operations require linear time
    for their worst-case behavior?

       A. is_empty
       B. peek
       C. pop
       D. push when the stack is below capacity
       E. None of these operations require linear time.

14. In the linked-list version of the Stack class, which operations require linear
    time for their worst-case behavior?

       A. is_empty
       B. peek
       C. pop
       D. push
       E. None of these operations require linear time.

15. What is the value of the postfix expression 6 3 2 4 + - *:

       A. Something between -15 and -100
       B. Something between -5 and -15
       C. Something between 5 and -5
       D. Something between 5 and 15
       E. Something between 15 and 100
 16. Here is an infix expression: 4+3*(6*3-12). Suppose that we are using the
     usual Stack algorithm to convert the expression from infix to postfix notation.
     What is the maximum number of symbols that will appear on the stack AT
     ONE TIME during the conversion of this expression?

        A. 1
        B. 2
        C. 3
        D. 4
        E. 5
                                    QUEUES

  1. Complete the body of this method. Use a CharQueue to store the input line as
       it is being read. The parameter is an EasyReader from Appendix B of the text.
       Use the method in.charInput( ) to read and return the next character of the
       EasyReader, and use in.isEOLN( ) to determine whether the next input
       character is the end-of-line.
   public static int counter(EasyReader in)
   // Precondition: There is a line of input waiting to be read from in.
   // Postcondition: A line of input has been read from in, up to but not
   // including the newline character. The return value of the method
   // is the number of times that the LAST character of the line appeared
   // somewhere in this line.
   // EXAMPLE Input: ABBXDXXZX
   // The value returned by counter would be 4 for this input since there
   // are 4 X's in the input line.
i.     I am going to execute this code with THREE inserts and ONE get_front:
   IntQueue q = new IntQueue( );
   q.insert(1);
   q.insert(2);
   q.insert(3);
   System.out.println(q.getFront( ));

    Suppose that q is represented by a circular array. Draw the state of these
    private instance variables of q after the above code:


      _______ __________________________________
      front| | data| | | | | |
      |_______| |______|______|______|______|______|
      [0] [1] [2] [3] [4]
  ii.    I am going to execute this code with THREE insert and ONE get_front:
 IntQueue q = new IntQueue( );
 q.insert(1);
 q.insert(2);
 q.insert(3);
 System.out.println(q.getFront( ));

    Suppose that q is represented by a linked list. Draw the state of the private
    instance variables of q after the above code:

     _______
     front| |
     |_______|
       _______
       rear| |
       |_______|

   2. Describe why it is a bad idea to implement a linked list version a queue which
      uses the head of the list as the rear of the queue.
   3. Suppose that you want to implement the PriorityQueue so that insertions
      occur in constant time, but getFront requires linear time. You will use these
      class definitions, where the data entering the PriorityQueue is a String and
      the priorities are ints.

         public class PriorityQueue
         {
         // A PriorityNode is a node from a linked list of strings, with
         // methods for getString, setString, getPriority, setPriority,
         // getLink, and setLink.
         private PriorityNode head;

         public void insert(String entry, int priority)...
         public String getFront( )...
         ...
         }
      (A) Write ONE sentence to describe how the insert method will work (with
      constant time).
      (B) Then implement the getFront method (which will have linear worst-case
      time). In your implementation, you DO NOT have to worry about items with
      equal priority (they may come out of the prioirty queue however you like,
      without necessarily having FIFO behavior). To remove the head node of a
      linked list, use the assignment:
       head = head.getLink( );

Multiple Choice

   1. One difference between a queue and a stack is:

          A. Queues require linked lists, but stacks do not.
          B. Stacks require linked lists, but queues do not.
          C. Queues use two ends of the structure; stacks use only one.
          D. Stacks use two ends of the structure, queues use only one.

   2. If the characters 'D', 'C', 'B', 'A' are placed in a queue (in that order), and
      then removed one at a time, in what order will they be removed?

          A. ABCD
          B. ABDC
          C. DCAB
          D. DCBA

   3. Which of the following expressions evaluates to true with approximate
      probability equal to P? (P is double and 0 <= P <= 1).

          A. Math.random() < P
          B. Math.random() > P
       C. Math.random() < P * 100
       D. Math.random() > P * 100

4. Suppose we have a circular array implementation of the queue class, with ten
   items in the queue stored at data[2] through data[11]. The current capacity
   is 42. Where does the insert method place the new entry in the array?

       A. data[1]
       B. data[2]
       C. data[11]
       D. data[12]

5. Consider the implementation of the Queue using a circular array. What goes
   wrong if we try to keep all the items at the front of a partially-filled array (so
   that data[0] is always the front).

       A. The constructor would require linear time.
       B. The getFront method would require linear time.
       C. The insert method would require linear time.
       D. The isEmpty method would require linear time.

6. In the linked list implementation of the queue class, where does the insert
   method place the new entry on the linked list?

       A. At the head
       B. At the tail
       C. After all other entries that are greater than the new entry.
       D. After all other entries that are smaller than the new entry.

7. In the circular array version of the Queue class, which operations require
   linear time for their worst-case behavior?

       A. getFront
       B. insert when the capacity has not yet been reached
       C. isEmpty
       D. None of these operations require linear time.

8. In the linked-list version of the Queue class, which operations require linear
   time for their worst-case behavior?

       A. getFront
       B. insert
       C. isEmpty
       D. None of these operations require linear time.

9. If data is a circular array of CAPACITY elements, and rear is an index into that
   array, what is the formula for the index after rear?

       A. (rear % 1) + CAPACITY
       B. rear % (1 + CAPACITY)
       C. (rear + 1) % CAPACITY
       D. rear + (1 % CAPACITY)
10. I have implemented the queue with a circular array, keeping track of front,
    rear, and manyItems (the number of items in the array). Suppose front is
    zero, and rear is one less than the current capacity. What can you tell me
    about manyItems?

       A. manyItems must be zero.
       B. manyItems must be equal to the current capacity.
       C. count could be zero or the capacity, but no other values could occur.
       D. None of the above.

11. I have implemented the queue with a linked list, keeping track of a front node
    and a rear node with two reference variables. Which of these reference
    variables will change during an insertion into a NONEMPTY queue?

       A. Neither changes
       B. Only front changes.
       C. Only rear changes.
       D. Both change.

12. I have implemented the queue with a linked list, keeping track of a front node
    and a rear node with two reference variables. Which of these reference
    variables will change during an insertion into an EMPTY queue?

       A. Neither changes
       B. Only front changes.
       C. Only rear changes.
       D. Both change.

13. Suppose getFront is called on a priority queue that has exactly two entries
    with equal priority. How is the return value of getFront selected?

       A. One is chosen at random.
       B. The one which was inserted first.
       C. The one which was inserted most recently.
       D. This can never happen (violates the precondition)

14. An array of queues can be used to implement a priority queue, with each
    possible priority corresponding to its own element in the array. When is this
    implementation not feasible?

       A. When the number of possible priorities is huge.
       B. When the number of possible priorities is small.
       C. When the queues are implemented using a linked list.
       D. When the queues are implemented with circular arrays.
                                SEARCHING


1. Here is an array with exactly 15 elements:

      1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

   Suppose that we are doing a serial search for an element. Circle any elements
   that will be found by examining two or fewer numbers from the array.

2. Here is an array with exactly 15 elements:

      1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

   Suppose that we are doing a binary search for an element. Circle any
   elements that will be found by examining two or fewer numbers from the
   array.

3. Implement the body of the following function using a binary search of the
   array. You do not need to check the precondition. All your local variables
   must be size_t variables.

    bool has_42(const int data[ ], size_t n)
    // Precondition: The elements data[0]...data[n-1] are sorted from smallest
    // to largest. The value of n might be zero (indicating an empty
    // array).
    // Postcondition: A true return value indicates that the number 42 appears in
    // data[0]...data[n-1]. A false return value indicates that 42 doesn’t appear.

4. Draw a hash table with open addressing and a size of 9. Use the hash
   function "k%9". Insert the keys: 5, 29, 20, 0, 27 and 18 into your table (in
   that order).
5. Suppose you are building an open address hash table with double hashing.
   The hash table capacity is n, so that the valid hash table indexes range from
   0 to n. Fill in the blanks:
        o In order to ensure that every array position is examined, the value
            returned by the second hash function must be
            ________________________ with respect to n.
        o One way to ensure this good behavior is to make n be
            _______________, and have the return value of the second hash
            function range from _________ to _________ (including the end
            points).
6. You are writing code for the remove member function of a chained hash table.
   Fill in the blanks in this pseudocode with the two missing statements. You
   may use pseudocode yourself, or write actual C++ code:

      void Table::remove(int key)
      {
      Node cursor;
      size_t i;

      1. i = hash(key);
      2. Make cursor point to the node that contains an item with the given key
      (or set it to NULL if there is no such node).

      3. if (cursor != NULL)
      {
      3a.
     ____________________________________________________________
     _

      3b.
     ____________________________________________________________
     _
      }

7. Draw a hash table with chaining and a size of 9. Use the hash function "k%9"
   to insert the keys 5, 29, 20, 0, and 18 into your table.
8. Suppose that I have the following record_type definition for a record in a hash
   table:
      struct record_type
      {
      int key;
      ... other stuff may also appear here ...
      };
          The hash table uses open addressing with linear probing. The table size
          is a global constant called CAPACITY. Locations of the table that have
          NEVER been used will contain the key -1. Locations of the table that
          were once used but are now vacant will contain the key -2. All valid keys
          will be non-negative, and the hash function is:
           size_t hash(int key)
           {
           return (key % CAPACITY);
           }

   Complete the implementation of the following function. There is no need to
   check the precondition, but your code must be as efficient as possible.

   bool key_occurs(const record_type data[ ], int search_key)
   // Precondition: data[0]...data[CAPACITY-1] is an open address hash table
   // as described above.
   // Postcondition: If search_key occurs as a key of a record in the table, then
   // the function returns true; otherwise the function returns false.

9. Suppose that an open-address hash table has a capacity of 811 and it
    contains 81 elements. What is the table's load factor? (An appoximation is
    fine.)
10. I plan to put 1000 items in a hash table, and I want the average number of
    accesses in a successful search to be about 2.0.

   A. About how big should the array be if I use open addressing with linear
   probing? NOTE: For a load factor of A, the average number of accesses is
   generally ½(1+1/(1-A)).
      B. About how big should the array be if I use chained hashing? NOTE: For a
      load factor of A, the average number of accesses is generally (1+A/2).

Multiple Choice

   1. What is the worst-case time for serial search finding a single item in an array?

          A. Constant time
          B. Logarithmic time
          C. Linear time
          D. Quadratic time

   2. What is the worst-case time for binary search finding a single item in an
      array?

          A. Constant time
          B. Logarithmic time
          C. Linear time
          D. Quadratic time

   3. What additional requirement is placed on an array, so that binary search may
      be used to locate an entry?

          A. The array elements must form a heap.
          B. The array must have at least 2 entries.
          C. The array must be sorted.
          D. The array's size must be a power of two.

   4. What is the best definition of a collision in a hash table?

          A. Two entries are identical except for their keys.
          B. Two entries with different data have the exact same key.
          C. Two entries with different keys have the same exact hash value.
          D. Two entries with the exact same key have different hash values.

   5. Which guideline is NOT suggested from from empirical or theoretical studies
      of hash tables:

          A. Hash table size should be the product of two primes.
          B. Hash table size should be the upper of a pair of twin primes.
          C. Hash table size should have the form 4K+3 for some K.
          D. Hash table size should not be too near a power of two.

   6. In an open-address hash table there is a difference between those spots
      which have never been used and those spots which have previously been
      used but no longer contain an item. Which function has a better
      implementation because of this difference?

          A. insert
          B. is_present
          C. remove
          D. size
       E. Two or more of the above functions

7. What kind of initialization needs to be done for an open-address hash table?

       A. None.
       B. The key at each array location must be initialized.
       C. The head pointer of each chain must be set to NULL.
       D. Both B and C must be carried out.

8. What kind of initialization needs to be done for an chained hash table?

       A. None.
       B. The key at each array location must be initialized.
       C. The head pointer of each chain must be set to NULL.
       D. Both B and C must be carried out.

9. A chained hash table has an array size of 512. What is the maximum number
   of entries that can be placed in the table?

       A. 256
       B. 511
       C. 512
       D. 1024
       E. There is no maximum.

10. Suppose you place m items in a hash table with an array size of s. What is
    the correct formula for the load factor?

       A. s + m
       B. s - m
       C. m - s
       D. m * s
       E. m / s
                                COMPLEXITY


1. Why is the order of an algorithm generally more important than the speed of
   the processor?
2. Convert each time formula to the best possible big-O notation. Do not include
   any spurious constants in your big-O answer.


                             Time Formula         Big-O
                       10n                        .
                       2n²                        .
                       3 times log (base 2) of n .
                       2n² + 10n                  .


3. What does a run-time analysis usually count?
       A. The number of arithmetic and other operations required for the
       program to run
       B. The number of megabytes required for the program to run
       C. The number of seconds required for the program to run
       D. The number of seconds plus the number of megabytes
       E. The number of seconds times the number of megabytes

4. Which of these is the correct big-O expression for 1+2+3+...+n

       A. O(log n)
       B. O(n)
       C. O(n log n)
       D. O(n²)

4. Which of the following formulas in big-O notation best represent the
   expression n²+35n+6?

       A. O(n³)
       B. O(n²)
       C. O(n)
       D. O(42)

5. Answer true or false for this statement: For all possible inputs, a linear
   algorithm to solve a problem must perform faster than a quadratic algorithm
   to solve the same problem.

       TRUE.
       FALSE.

6. Answer true or false for this statement: True or false: An algorithm with worst
   case time behavior of 3n takes at least 30 operations for every input of size
   n=10.

       TRUE.
       FALSE.

7. What term is used to describe an O(n) algorithm.

       A. Constant
       B. Linear
       C. Logarithmic
       D. Quadratic

8. Here is some code for an integer variable n:

      while (n > 0)
      {
      n = n/10; // Use integer division
      }

   What is the worst-case time analysis for the above loop?
        A. O(1)
        B. O(log n)
        C. O(n)
        D. O(n²)

9. Express the formula (n - 2)*(n - 4) using big-O notation:

        A. O(1)
        B. O(8)
        C. O(log n)
        D. O(n)
        E. None of the above

                                     TREES

1. Here is a small binary tree:

         14
         / \
         2 11
         / \ / \
         1 3 10 30
         / /
         7 40
     Circle all the leaves. Put a square box around the root. Draw a star around
     each ancestor of the node that contains 10. Put a big X through every
     descendant of the node that contains 10.
2.   Draw a full binary tree with at least 6 nodes.
3.   Draw a complete binary tree with exactly six nodes. Put a different value in
     each node. Then draw an array with six components and show where each of
     the six node values would be placed in the array (using the usual array
     representation of a complete binary tree).
4.   Write the instance variables for a new class that could be used for a node in a
     tree where: (1) Each node contains int data, (2) Each node has up to four
     children, and (3) Each node also has a reference to its parent. Store the
     references to the children in an array of four components.
5.   Draw a binary taxonomy tree that can be used for these four animals: Rabbit,
     Horse, Whale, Snake.
6.   Using the BTNode class from Chapter 9, write a new static method of the
     BTNode class to meet the following specification. No recursion is needed.

     public static void subswap(BTNode root)
     // Precondition: Root is the root reference of a binary tree.
     // Postcondition: If root is non-null, then the original left
     subtree below
     // this root has been moved and is now the right subtree, and the
     original
     // right subtree is now the left subtree.
     // Example original tree: Example new tree:
     // 1     1
     // / \ / \
     // 2 3 3 2
     // / \ / \
     // 4 5 4 5
7. Redo the previous problem as a new non-static BTNode method.
8. Using the BTNode class from Chapter 9, write a new static method of the
   BTNode class to meet the following specification.

   public static void flip(BTNode root)
   // Precondition: Root is the root reference of a binary tree.
   // Postcondition: If the root is non-null, then the tree below
   this node is
   // now the mirror image of its original value.
   // Example original tree: Example new tree:
   // 1    1
   // / \ / \
   // 2 3 3 2
   // / \ / \
   // 4 5 5 4

9. Redo the previous problem as a new non-static BTNode method.
10. Here is a small binary tree:

      14
      / \
       2 11
      / \ / \
      1 3 10 30
      / /
      7 40
   Write the order of the nodes visited in:
   A. An in-order traversal:
   B. A pre-order traversal:
   C. A post-order traversal:

11. Suppose IntBTNode is a BTNode (from Chapter 9) with integer data. Write a
    new static method of the IntBTNode class to meet the following specification .

   public static void increase(IntBTNode root)
   // Precondition: root is the root reference of a binary tree.
   // Postcondition: Every node of the tree has had its data
   // increased by one.

   12. Redo the previous problem as a new non-static BTNode method.
   13. Using the BTNode class from Chapter 9, write a new static method of the
       BTNode class to meet the following specification.

   public static int manyNodes(BTNode root)
   // Precondition: root_ptr is the root reference of a binary tree.
   // Postcondition: The return value is the number of nodes in the
   tree.
   // NOTES: The empty tree has 0 nodes, and a tree with just a root
   has
   // 1 node.

14. Using the BTNode class from Chapter 9, write a new static method of the
    BTNode class to meet the following specification.

   public static int treeDepth(BTNode root)
     // Precondition: root_ptr is the root reference of a binary tree.
     // Postcondition: The return value is the depth of the binary
     tree.
     // NOTES: The empty tree has a depth of -1 and a tree with just a
     root
     // has a depth of 0.

 15. Suppose IntBTNode is a BTNode (from Chapter 9) with integer data. Write a
     new static method of the IntBTNode class to meet the following specification.

     public static int count42(IntBTNode root)
     // Precondition: root is the root reference of a binary tree (but
     // NOT NECESSARILY a search tree).
     // Postcondition: The return value indicates how many times 42
     appears
     // in the tree. NOTE: If the tree is empty, the method returns
     zero.

 16. Suppose IntBTNode is a BTNode (from Chapter 9) with integer data. Write a
     new static method of the IntBTNode class to meet the following specification.

     public static boolean has42(IntBTNode root)
     // Precondition: root is the root reference of a binary tree (but
     // NOT NECESSARILY a search tree).
     // Postcondition: The return value indicates whether 42 appears
     somewhere
     // in the tree. NOTE: If the tree is empty, the method returns
     false.

 17. Suppose IntBTNode is a BTNode (from Chapter 9) with integer data. Write a
     new static method of the IntBTNode class to meet the following specification.

     public static boolean all42(IntBTNode root)
     // Precondition: root is the root reference of a binary tree (but
     // NOT NECESSARILY a search tree).
     // Postcondition: The return value is true if every node in the
     tree
     // contains 42. NOTE: If the tree is empty, the method returns
     true.

18. Suppose IntBTNode is a BTNode (from Chapter 9) with integer data. Write a
    new static method of the IntBTNode class to meet the following specification .

   public static int sum(IntBTNode root)
   // Precondition: root is the root reference of a binary tree.
   // Postcondition: The return value is the sum of all the data in
   all the nodes.
   // NOTES: The return value for the empty tree is zero.

 19. Suppose that we want to create a binary search tree where each node
     contains information of some data type. What additional factor is required for
     the data type?
 20. Suppose that a binary search tree contains the number 42 at a node with two
     children. Write two or three clear sentences to describe the process required
     to delete the 42 from the tree.
   21. Suppose IntBTNode is a BTNode (from Chapter 9) with integer data. Write a
       new static method of the IntBTNode class to meet the following specification.
       Make the method as efficient as possible (do not visit nodes unnecessarily).

      public static int count42(BTNode root)
      // Precondition: root is the root reference of a binary SEARCH
      tree.
      // Postcondition: The return value indicates how many times 42
      appears
      // in the tree.

   22. Suppose IntBTNode is a BTNode (from Chapter 9) with integer data. Write a
       new static method of the IntBTNode class to meet the following specification.
       Make the method as efficient as possible (do not visit nodes unnecessarily).

      public static int max(BTNode root)
      // Precondition: root is the root reference of a nonempty binary
      SEARCH
      // tree.
      // Postcondition: The return value is the largest value in the
      tree.

   23. Suppose IntBTNode is a BTNode (from Chapter 9) with integer data. Write a
       new static method of the IntBTNode class to meet the following specification.
       Make the method as efficient as possible (do not visit nodes unnecessarily).

      void insert42(BTNode root)
      // Precondition: root is the root reference of a binary SEARCH
      tree.
      // Postcondition: One copy of the number 42 has been added to the
      binary
      // search tree.

Multiple Choice

   1. There is a tree in the box at the top of this section. How many leaves does it
      have?

          A. 2
          B. 4
          C. 6
          D. 8
          E. 9

   2. There is a tree in the box at the top of this section. How many of the nodes
      have at least one sibling?

         A. 5
         B. 6
         C. 7
         D. 8
         E. 9
   3. There is a tree in the box at the top of this section. What is the value stored
      in the parent node of the node containing 30?
       A. 10
       B. 11
       C. 14
       D. 40
       E. None of the above

4. There is a tree in the box at the top of this section. How many descendants
   does the root have?

       A. 0
       B. 2
       C. 4
       D. 8

5. There is a tree in the box at the top of this section. What is the depth of the
   tree?

       A. 2
       B. 3
       C. 4
       D. 8
       E. 9

6. There is a tree in the box at the top of this section. How many children does
   the root have?

       A. 2
       B. 4
       C. 6
       D. 8
       E. 9

7. Consider the binary tree in the box at the top of this section. Which statement
   is correct?

       A. The tree is neither complete nor full.
       B. The tree is complete but not full.
       C. The tree is full but not complete.
       D. The tree is both full and complete.

8. What is the minimum number of nodes in a full binary tree with depth 3?

       A. 3
       B. 4
       C. 8
       D. 11
       E. 15

9. What is the minimum number of nodes in a complete binary tree with depth
   3?

       A. 3
       B. 4
       C. 8
       D. 11
       E. 15

10. Select the one true statement.

       A. Every binary tree is either complete or full.
       B. Every complete binary tree is also a full binary tree.
       C. Every full binary tree is also a complete binary tree.
       D. No binary tree is both complete and full.

11. Suppose T is a binary tree with 14 nodes. What is the minimum possible
    depth of T?

       A. 0
       B. 3
       C. 4
       D. 5

12. Select the one FALSE statement about binary trees:

       A. Every binary tree has at least one node.
       B. Every non-empty tree has exactly one root node.
       C. Every node has at most two children.
       D. Every non-root node has exactly one parent.

13. Suppose t is a BTNode variable from Chapter 9, which expression indicates
    that t represents an empty tree?

       A. (t == null)
       B. (t->data == 0)
       C. (t->data == null)
       D. ((t->left == null) && (t->right == null))

14. Consider the node of a complete binary tree whose value is stored in data[i]
    for an array implementation. If this node has a right child, where will the right
    child's value be stored?

       A. data[i+1]
       B. data[i+2]
       C. data[2*i + 1]
       D. data[2*i + 2]

15. Suppose that a binary taxonomy tree includes 8 animals. What is the
    minimum number of NONLEAF nodes in the tree?

       A. 1
       B. 3
       C. 5
       D. 7
       E. 8
16. There is a tree in the box at the top of this section. What is the order of nodes
    visited using a pre-order traversal?

       A. 1 2 3 7 10 11 14 30 40
       B. 1 2 3 14 7 10 11 40 30
       C. 1 3 2 7 10 40 30 11 14
       D. 14 2 1 3 11 10 7 30 40

17. There is a tree in the box at the top of this section. What is the order of nodes
    visited using an in-order traversal?

       A. 1 2 3 7 10 11 14 30 40
       B. 1 2 3 14 7 10 11 40 30
       C. 1 3 2 7 10 40 30 11 14
       D. 14 2 1 3 11 10 7 30 40

18. There is a tree in the box at the top of this section. What is the order of nodes
    visited using a post-order traversal?

       A. 1 2 3 7 10 11 14 30 40
       B. 1 2 3 14 7 10 11 40 30
       C. 1 3 2 7 10 40 30 11 14
       D. 14 2 1 3 11 10 7 30 40

19. Consider this binary search tree:

           14
           / \
           2 16
           / \
           1 5
           /
           4
   Suppose we remove the root, replacing it with something from the left
   subtree. What will be the new root?
      A. 1
      B. 2
      C. 4
      D. 5
      E. 16
                                   HEAPS


1. Suppose that we want to create a heap where each node contains information
   of some data type. What additional factor is required for the data type?
2. A heap is a binary tree where the entries can be compared using the usual six
   comparison operations (that form a total order semantics). Write the two
   rules that the binary tree must follow in order for the structure to actually be
   a heap.
3. Give two different reasons to explain why the following binary tree is not a
   heap:

      91
      / \
      77 46
      / \ \
      68 81 11

4. Draw a new heap that is created by inserting 82 into the following heap:

      910
      / \
      77 66
      / \ / \
      68 1 3 11

5. Draw a new heap that is created by removing one item from the following
   heap:

      910
      / \
      77 66
      / \ / \
      68 1 3 11

6. Suppose that you are performing a reheapification downward. Write a precise
    condition that describes the situation that causes the reheapification to stop.
7. Suppose that you are performing a reheapification upward. Write a precise
    condition that describes the situation that causes the reheapification to stop.
8. Suppose that a non-leaf node in a B-tree contains 42 entries. How many
    children does the node have?
9. Draw an example of a B-tree with four nodes and seven integer entries. The
    value of MINIMUM is 1 for this tree.
10. Draw a new B-tree that is created by inserting 82 into the following B-tree.
    For this example, the minimum number of items in each node is 1. Note that
    the rightmost leaf starts with two entries, 71 and 93.

      56
      / \
      7 66
      / \ / \
      2 8 63 71 and 93

11. Draw a new B-tree that is created by deleting 63 from the following B-tree.
    For this example, the minimum number of items in each node is 1. Note that
    the rightmost leaf starts with two entries, 71 and 93.

      56
      / \
      7 66
      / \ / \
      2 8 63 71 and 93

12. Suppose that a B-tree is declared so that MAXIMUM (the maximum number of
    items in a node) is 84. What is the value of MINIMUM (the minimum number
    of items in a non-root node)?
   13. Suppose that a B-tree is declared so that MAXIMUM (the maximum number of
       items in a node) is 84. Write one clear sentence to describe why each node's
       data array is set up to hold up to 85 items (one more than MAXIMUM).
   14. Suppose that a and b are two positive integers and n is some non-negative
       number. Write an equation to show the relationship between log base a of n
       and log base b of n. Give a derivation to show that the relationship is valid.

Multiple Choice

   1. What feature of heaps allows them to be efficiently implemented using a
      partially filled array?

          A. Heaps are binary search trees.
          B. Heaps are complete binary trees.
          C. Heaps are full binary trees.
          D. Heaps contain only integer data.

   2. If a heap is implemented using a partially filled array called data, and the
      array contains n elements (n > 0), where is the entry with the greatest value?

          A. data[0]
          B. data[n-1]
          C. data[n]
          D. data[2*n + 1]
          E. data[2*n + 2]

   3. Select the true statement about the worst-case time for operations on heaps.

          A. Niether insertion nor removal is better than linear.
          B. Insertion is better than linear, but removal is not.
          C. Removal is better than linear, but insertion is not.
          D. Both insertion and removal are better than linear.

   4. Suppose that we have implemented a priority queue by storing the items in a
      heap (using an array for the heap items). We are now executing a
      reheapification upward and the out-of-place node is at data[i] with priority
      given by data[i].priority. Which of the following boolean expressions is TRUE
      to indicate that the reheapification IS NOT YET DONE.

          A. (i > 0)
          B. (data[(i-1)/2].priority < data[i].priority)
          C. (i > 0) && (data[(i-1)/2].priority < data[i].priority)
          D. (i > 0) || (data[(i-1)/2].priority < data[i].priority)

   4. Suppose that we have implemented a priority queue by storing the items in a
      heap. We are now executing a reheapification downward and the out-of-place
      node has priority of 42. The node's parent has a priority of 72, the left child
      has priority 52 and the node's right child has priority 62. Which statement
      best describes the status of the reheapification.

          A. The reheapification is done.
          B. The next step will interchange the two children of the out-of-place
          node.
       C. The next step will swap the out-of-place node with its parent.
       D. The next step will swap the out-of-place node with its left child.
       E. The next step will swap the out-of-place node with its right child.

5. Which formula is the best approximation for the depth of a heap with n
   nodes?

       A. log (base 2) of n
       B> The number of digits in n (base 10)
       C. The square root of n
       D. n
       E. The square of n

6. Which statement is true for a B-tree?

       A. All entries of a node are greater than or equal to the entries in the
       node's children.
       B. All leaves are at the exact same depth.
       C. All nodes contain the exact same number of entres.
       D. All non-leaf nodes have the exact same number of children.

7. Suppose that a non-leaf node in a B-tree has 41 entries. How many children
   will this node have?

       A. 2
       B. 40
       C. 41
       D. 42
       e. 82

8. Suppose that a B-tree has MAXIMUM of 10 and that a node already contains
   the integers 1 through 10. If a new value, 11, is added to this node, the node
   will split into two pieces. What values will be in these two pieces?

       A. The first piece will have only 1 and the second piece will have the rest
       of the numbers.
       B. The first piece will have 1 through 5 and the second piece will have 6
       through 11.
       C. The first piece will have 1 through 5 and the second piece will have 7
       through 11.
       D. The first piece will have 1 through 6 and the second piece will have 7
       through 11.
       E. The first piece will have 1 through 10 and the second piece will have
       only 11.

9. Suppose that X is a B-tree leaf containing 41 entries and having at least one
   sibling. Which statement is true?

       A. Any sibling of X is also a leaf.
       B. Any sibling of X contains at least 41 entries.
       C. The parent of X has exactly 42 entries.
       D. X has at least 41 siblings.
10. Suppose you run a O(log n) algorithm with an input size of 1000 and the
    algorithm requires 110 operations. When you double the input size to 2000,
    the algorithm now requires 120 operations. What is your best guess for the
    number of operations required when you again double the input size to 4000?

       A. 130
       B. 140
       C. 150
       D. 160
       E. 170

11. Tree algorithms typically run in time O(d) . What is d?

       A. The depth of the tree.
       B. The number of divisions at each level.
       C. The number of entries in each node.
       D. The number of nodes in the tree.
       E. The total number of entries in all the nodes of the tree.
                                  SORTING


1. Here is an array of ten integers:

      5 3 8 9 1 7 0 2 6 4

   Draw this array after the FIRST iteration of the large loop in a selection sort
   (sorting from smallest to largest).

2. Here is an array of ten integers:

       5 3 8 9 1 7 0 2 6 4
   Draw this array after the FIRST iteration of the large loop in an insertion sort
   (sorting from smallest to largest). This iteration has shifted at least one item
   in the array!

3. Suppose that you are writing a program that has this selectionsort static
   method available:

 void selectionsort(int[ ] data, int first, int n);

   Your program also has an integer array called x, with 10 elements. Write two
   method activations: The first activation uses selectionsort to sort all of x; the
   second call uses selectionsort to sort x[3]..x[9].

4. Describe a case where quicksort will result in quadratic behavior.
5. Here is an array which has just been partitioned by the first step of quicksort:
      3, 0, 2, 4, 5, 8, 7, 6, 9
   Which of these elements could be the pivot? (There may be more than one
   possibility!)
6. Give a concise accurate description of a good way for quicksort to choose a
   pivot element. Your approach should be better than "use the entry at location
   [0]".
7. Give a concise accurate description of a good way for quicksort to improve its
    performance by using insertionsort.
8. Here is an array of ten integers:
       5 3 8 9 1 7 0 2 6 4
    Suppose we partition this array using quicksort's partition function and using
    5 for the pivot. Draw the resulting array after the partition finishes.
9. Here is an array of ten integers:
       5 3 8 9 1 7 0 2 6 4
    Draw this array after the TWO recursive calls of merge sort are completed,
    and before the final merge step has occured.
10. Implement the following static method:
       private static void merge(int[ ] data, int first, int n1, int
      n2);
       // Precondition: data has at least n1+n2 components starting at
       // data[first]. The first n1 elements (from data[first] to
       // data[first+n1-1]) are sorted from smallest to largest, and
      the last
       // n2 elements (from data[first+n1] to data[first+n1+n2-1]) are
      also
       // sorted from smallest to largest.
       // Postcondition: Starting at data[first, n1+n2 elements of
      data have been
       // rearranged to be sorted from smallest to largest.

11. Write two or three clear sentences to describe how a heapsort works.
12. Fill in the following table for the times to sort an array of n items. Use only
    big-O notation, and do not have any extraneous constants in your
    expressions.


                                                         Worst         Average
                                                         Case          Case
   Binary search of a sorted array                       .             .
   Insertion sort                                        .             .
   Merge sort                                            .             .
   Quick sort without "median of three" pivot
                                                         .             .
   selection
   Quick sort with "median of three" pivot selection .                 .
   Selection sort                                        .             .
   Heap sort                                             .             .


13. (This question may not have been covered in your class.) Suppose that you
    implement quicksort nonrecursively using a stack, as in your last
    programming assignment. You use your algorithm to sort an array of 100
    items, and at the start of the final iteration of the while loop, the stack
    contains just two numbers: 10 (on top) and 90 (on bottom). Write one or two
    clear sentences to describe which parts of the array are sorted at this point,
    and which parts of the array remain to be sorted.
Multiple Choice

   1. In a selection sort of n elements, how many times is the swap function called
      in the complete execution of the algorithm?

          A. 1
          B. n - 1
          C. n log n
          D. n²

   2. Selection sort and quick sort both fall into the same category of sorting
      algorithms. What is this category?

          A. O(n log n) sorts
          B. Divide-and-conquer sorts
          C. Interchange sorts
          D. Average time is quadratic.

   3. Suppose that a selection sort of 100 items has completed 42 iterations of the
      main loop. How many items are now guaranteed to be in their final spot
      (never to be moved again)?

          A. 21
          B. 41
          C. 42
          D. 43

   4. Suppose we are sorting an array of ten integers using a some quadratic
      sorting algorithm. After four iterations of the algorithm's main loop, the array
      elements are ordered as shown here:

         1 2 3 4 5 0 6 7 8 9

      Which statement is correct? (Note: Our selectionsort picks largest items first.)

          A. The algorithm might be either selectionsort or insertionsort.
          B. The algorithm might be selectionsort, but could not be insertionsort.
          C. The algorithm might be insertionsort, but could not be selectionsort.
          D. The algorithm is neither selectionsort nor insertionsort.

   5. Suppose we are sorting an array of eight integers using a some quadratic
      sorting algorithm. After four iterations of the algorithm's main loop, the array
      elements are ordered as shown here:

       2 4 5 7 8 1 3 6

   6. Which statement is correct? (Note: Our selectionsort picks largest items first.)

          A. The algorithm might be either selectionsort or insertionsort.
          B. The algorithm might be selectionsort, but it is not insertionsort.
          C. The algorithm is not selectionsort, but it might be insertionsort.
          D. The algorithm is neither selectionsort nor insertionsort.
7. When is insertionsort a good choice for sorting an array?

       A. Each component of the array requires a large amount of memory.
       B. Each component of the array requires a small amount of memory.
       C. The array has only a few items out of place.
       D. The processor speed is fast.

8. What is the worst-case time for mergesort to sort an array of n elements?

       A. O(log n)
       B. O(n)
       C. O(n log n)
       D. O(n²)

9. What is the worst-case time for quicksort to sort an array of n elements?

       A. O(log n)
       B. O(n)
       C. O(n log n)
       D. O(n²)

10. Mergesort makes two recursive calls. Which statement is true after these
    recursive calls finish, but before the merge step?

       A. The array elements form a heap.
       B. Elements in each half of the array are sorted amongst themselves.
       C. Elements in the first half of the array are less than or equal to elements
       in the second half of the array.
       D. None of the above.

11. Suppose we are sorting an array of eight integers using quicksort, and we
    have just finished the first partitioning with the array looking like this:

 2 5 1 7 9 12 11 10

   Which statement is correct?

       A. The pivot could be either the 7 or the 9.
       B. The pivot could be the 7, but it is not the 9.
       C. The pivot is not the 7, but it could be the 9.
       D. Neither the 7 nor the 9 is the pivot.

12. What is the worst-case time for heapsort to sort an array of n elements?

       A. O(log n)
       B. O(n)
       C. O(n log n)
       D. O(n²)

13. Suppose we are sorting an array of eight integers using heapsort, and we
    have just finished one of the reheapifications downward. The array now looks
    like this:
         6 4 5 1 2 7 8

      How many reheapifications downward have been performed so far?

          A. 1
          B. 2
          C. 3 or 4
          D. 5 or 6
                                EXAM QUESTIONS

  1. How many of the trees in the margin are complete binary trees?
      A. None
      B. Two
      C. Three
      D. All


  2. How many of the trees in the margin are full binary trees?
      A. None
      B. Two
      C. Three
      D. All


  3. What is the maximum number of leaves for a binary tree with 15 nodes?
      A. Less than 8
      B. 8
      C. 9
      D. 10
      E. More than 10


  4. Consider a complete binary tree with 1000 nodes, with the data stored in the
     elements a[0]..a[999] of an array. Where are the parent and the left child of
     the node stored at a[100]?
       A. Parent at 49, left child at 200
       B. Parent at 49, left child at 201
       C. Parent at 50, left child at 200
       D. Parent at 50, left child at 201
     E. None of the above

  5. I am going to execute this code:
        Stack<int> s;
        s.push(1);
        s.push(2);
        s.push(3);
        cout << s.pop( );

A. Suppose that s is represented by a partially filled array. Draw the
state of the private member variables of s after the above code:
_______ __________________________________
used| | data| | | | | |
|_______| |______|______|______|______|______|
[0] [1] [2] [3] [4]
B. Suppose that s is represented by a linked list. Draw the linked list
after the above code:
_______
head_ptr| |
|_______|


  6. I am going to execute this code:
      Queue<int> q;
       q.insert(1);
       q.insert(2);
       q.insert(3);
       q.insert(4);
       q.insert(5);
       cout << q.get_front( );
       cout << q.get_front( );
       q.insert(6);

A. Suppose that q is represented by a partially filled array with a
CAPACITY of 5. Draw the state of the private member variables of q
after the above code:
        _______ __________________________________
         front| | data| | | | | |
         |_______| |______|______|______|______|______|
         [0] [1] [2] [3] [4]
         _______
         rear | |
        |_______|

       B. Suppose that q is represented by a linked list. Draw the linked list
       after the above code:
       _______ _______
       head_ptr| | | |rear_ptr
       |_______| |_______|


  7. Implement the following function. You may use the Stack template class and
     the Stack operations of push, pop, peek, is_empty, and size.
      You may also use cin.peek( ) and use "cin >> i" to read an integer.

  8. Suppose that you want to implement the PriorityQueue so that insertions
     occur in constant time, but get_front requires linear time. You will use these
     class definitions:

         class PriorityQueue
         {
         typedef double Item;
         ...
         private:
         Node *head_ptr;
         };
         struct Node
         {
         PriorityQueue::Item data;
         unsigned int priority;
      Node *link;
      };

     A. Write the PriorityQueue's insert member function:
     B. This question continues from the previous page. Write a description of the
    linear time get_front member function. Use drawings to show a typical
    example of how get_front will work when the PriorityQueue has five items
    with priorities 1, 10, 3, 10, and 6.
9. Write a recursive function that has one parameter which is a size_t value
    called x. The function prints x asterisks, followed by x exclamation points.
10. Implement the following function. Do not use any local variables or loops.

   void pattern(unsigned int n)
   // Precondition: n > 0;
   // Postcondition: The output consists of lines of integers. The
   first line
   // is the number n. The next line is the number 2n. The next line
   is
   // the number 4n, and so on until you reach a number that is
   larger than
   // 4242. This list of numbers is then repeated backward until you
   get back
   // to n.

   Example output with n = 840:
   840
   1680
   3360
   6720
   6720
   3360
   1680
   840

11. This question will help identify the A+ students. If you don't solve this
    problem, then don't worry, but do think about the problem after class. This
    question involves a game with teddy bears. The game starts when I give you
    some bears. You can then give back some bears, but each time that you give
    back some bears you must give back half of all your bears. (If you have n
    bears, and n is even, then you will give back n/2. If n is odd, then you may
    round down to give back (n-1)/2 bears, or you may round up to give back
    (n+1)/2 bears.) The goal of the game is to end up with EXACTLY 42 bears.
    For example, suppose that you start with 337 bears. Then you could make
    these moves:
     Start with 337 bears.
     Give back 168 (which is half of 337, rounding down) to leave 169 bears.
     You now have 169 bears.
     Give back 85 (which is half of 169, rounding up) to leave 84 bears.
     You now have 84 bears.
     Give back 42 (which is half of 42), to leave 42 bears.
     You have reached the goal!

   Write a recursive function to meet this specification:
   bool bears(int n)
   // Postcondition: A true return value means that it is possible to win
   // the bear game by starting with n bears. A false return value means that
     // it is not possible to win the bear game by starting with n bears.
     // Examples:
     // bear(337) is true (as shown above)
     // bear(42) is true
     // bear(83), bear(84) and bear(85) are all true
     // bear(52) is false
     // bear(41) is false
     {
      // Hint: To test whether n is even, use the expression ((n % 2) == 0).

     Write a declaration of a struct that could be used to store the data from a
     node in a tree, where each node has integer data and each node can have
     zero to 1000 children. Write the complete declaration in an exact form that
     will compile correctly. Do not omit any part of the declaration.

  12. Here is a complete binary tree. How would the values of these nodes be
      stored in an array, using the usual technique for storing a complete binary
      tree in an array? Draw your array below the tree.

                          _______
                         | 8 |
                         |_______|
                     ______/      \__________
                _______/                  \_______
               | 4 |                   | 10 |
               |_______|                  |_______|
               /    \                 /
          _______ /      \_______        _______/
         | 2 |        | 6 |       | 9 |
         |_______|       |_______|      |_______|


     Here is a binary tree.
                          _______
                         | 8 |
                         |_______|
                     ______/      \__________
                _______/                  \_______
               | 4 |                   | 10 |
               |_______|                  |_______|
               /    \                 /
          _______ /      \_______        _______/
         | 2 |        | 6 |       | 9 |
         |_______|       |_______|      |_______|


     A. In what order would the nodes of this tree be processed for an
      in-order traversal?
     B. In what order would the nodes of this tree be processed for a
      pre-order traversal?
     C. In what order would the nodes of this tree be processed for a
      post-order traversal?

Concept Map:
Course Contents:


                                    UNIT I

  1. Introduction

         o    1.1 Some Definitions
                  1.1.1 Four Fundamental Data Structures
          o 1.2 Complexity of Algorithms
                  1.2.1 Big Oh Notation
                  1.2.2 Examples
                  1.2.3 An Example: Complexity of Mergesort
                  1.2.4 Role of the Constant
                  1.2.5 Worst Case, Average Case, and Amortized Complexity
                  1.2.6 Big Omega and Big Theta Notations
                  1.2.7 An Example:
          o 1.3 To Probe Further
          o 1.4 Problems
     2. Lists
          o 2.1 List Abstract Data Type
                  2.1.1 A Program with List ADT
          o 2.2 Implementation of Lists
                  2.2.1 Array Implementation of Lists
                  2.2.2 Pointer Implementation of Lists
                  2.2.3 Doubly Linked List Implementation
          o 2.3 Stacks
          o 2.4 Queues
                  2.4.1 Pointer Implementation
                  2.4.2 Circular Array Implementation
                  2.4.3 Circular Linked List Implementation
          o 2.5 To Probe Further
          o 2.6 Problems

                                      UNIT II

     3. Dictionaries
          o 3.1 Sets
          o 3.2 Dictionaries
          o 3.3 Hash Tables
                  3.3.1 Open Hashing
          o 3.4 Closed Hashing
                  3.4.1 Rehashing Methods
                  3.4.2 An Example:
                  3.4.3 Another Example:
          o 3.5 Hashing Functions
                  3.5.1 Division Method
                  3.5.2 Multiplication Method
                  3.5.3 Universal Hashing
          o 3.7 Hash Table Restructuring
          o 3.8 Skip Lists
                  3.8.1 Initialization:
          o 3.10 To Probe Further
          o 3.11 Problems
                                      UNIT III

   6. Priority Queues
        o 6.1 Binary Heaps
                 6.1.1 Implementation of Insert and Deletemin
                 6.1.2 Creating Heap
        o 6.2 Binomial Queues
                 6.2.1 Binomial Queue Operations
                 6.2.2 Binomial Amortized Analysis
                 6.2.3 Lazy Binomial Queues
        o 6.3 To Probe Further
        o 6.4 Problems
   4. Binary Trees
        o 4.1 Introduction
                 4.1.1 Definitions
                 4.1.2 Preorder, Inorder, Postorder
                 4.1.3 The Tree ADT
                 4.1.4 Data Structures for Tree Representation
        o 4.2 Binary Trees
        o 4.4 Binary Search Tree
                 4.4.1 Average Case Analysis of BST Operations
        o 4.7 To Probe Further
        o 4.8 Problems
                 4.8.1 General Trees
                 4.8.2 Binary Search Trees

                                          UNIT IV

   5. Balanced Trees

       o   5.1 AVL Trees
               5.1.1 Maximum Height of an AVL Tree
               5.1.2 AVL Trees: Insertions and Deletions
       o   5.2 Splay Trees
               4.5.1 Search, Insert, Delete in Bottom-up Splaying
       o   5.2 Red-Black Trees
               5.2.1 Height of a Red-Black Tree
               5.2.2 Red-Black Trees: Insertions
               5.2.3 Red-Black Trees: Deletion
       o   5.3 2-3 Trees
               5.3.1 2-3 Trees: Insertion
               5.3.2 2-3 Trees: Deletion
       o   5.4 B-Trees
               5.4.1 Definition of B-Trees
               5.4.2 Complexity of B-tree Operations
               5.4.3 B-Trees: Insertion
               5.4.4 B-Trees: Deletion
               5.4.5 Variants of B-Trees
       o   5.5 To Probe Further
       o   5.6 Problems
               5.6.1 AVL Trees
               5.6.2 Red-Black Trees
               5.6.3 2-3 Trees and B-Trees
                                             UNIT V

     9. Sorting Methods
          o 9.1 Bubble Sort
          o 9.2 Insertion Sort
          o 9.3 Selection Sort
          o 9.4 Shellsort
          o 9.5 Heap Sort
          o 9.6 Quick Sort
          o 9.9 Radix Sorting
          o 9.10 Merge Sort
          o 9.11 To Probe Further
          o 9.12 Problems
     11. References and Resources
          o 11.1 Primary Sources for this Lecture Notes
          o 11.2 Useful Books
          o 11.3 Original Research Papers and Survey Articles
          o 11.4 Web Resources
     About this document ...

Module Level Learning Objectives:

				
DOCUMENT INFO