CSC 402 Review for Final
WITH SOLUTIONS -- with correction 6/6

Date/time/Location and Format

Materials and Topics


Review Questions

  1. Write a static method shuffle
      public static void shuffle(int[] data)

    This method shuffles the elements in the parameter int array (called 'data' in the header below).  The way to shuffle (called 'Fisher–Yates shuffle') is given by this pseudocode:
      for i from n − 1 downto 1 do
           j ← random integer such that 0 ≤ ji
           exchange a[j] and a[i]
    ANSWER:
     public static void shuffle(int[] data) {
      Random ran = new Random();
      int n = data.length;
      for (int i = data.length-1; i >= 1; --i) {
        int j = rgen.nextInt(i+1); // random int between 0 and i inclusive
        // swap those elements in data
        int temp = data[j];
        data[j] = data[i];
        data[i] = temp;
      }
    }
  2. What value is printed? Explain in a general term (rather than giving a specific value for the given specific array A.)
    public class M
    {
      public static int f(int[] arr, int i, int j)
      {
        int m;
        int b, c;
    
        if (i == j) {
          return arr[i];
        }
        else {
          m = (i + j) / 2;
          b = f(arr, i, m);
          c = f(arr, m + 1, j);
          if (b < c) {
            return b;
          }
          else {
            return c;
          }
        }
      }
    
      public static void main(String[] args)
      {
        int a;
        int[] A = {1,6,3,9,10,11,5};
       	   
        a = f(A, 0, A.length - 1);
     
        System.out.printf("a = %d\", a);
      }
    }
    ANSWER: The minimum value in the array.

  3. For the class Deque<E> from HW#3 (which uses a doubly linked list with dummy head + tail nodes), add the following methods. 
    1. public E peek()
      This method retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.

      ANSWER:

      public E peek() {
        if (isEmpty())
          return null;
        else 
          return head.next.data; // data is the name of the item field
      }
    2. public Deque<E> listUnion(Deque<E> lst2)
      This method returns a (new) Deque containing the elements from both queue's (with no duplicates).  Assume neither queue contains duplicates.  Order of the elements in the resulting queue is not relevant.

      ANSWER:

      public Deque<E> listUnion(Deque<E> lst2) {
        // (0) create the resulting queue
        Deque<E> lst3 = new Deque<E>();
      
        // (1) insert all (unique) elements from this list in lst3
        Iterator it1 = this.iterator();
        while (it.hasNext()) 
          lst3.addLast(it.next());
      
        // (2) insert other elements from lst2 in lst3  
        Iterator it2 = lst2.iterator();
        boolean found;
        while (it2.hasNext()) { 
          E val2 = it2.next();
          found = false;
          it1 = lst1.iterator(); // iterator to this list
          boolean found = false;
          while (it1.hasNext()) {
            E val1 = it1.next();
            if (val1.equals(val2)) { // same element exists in this list
              found = true;
              break;
            }
          }
          if (!found)
            lst3.addLast(val2);
        } // end outer-while
      
        return lst3;
      }
  4. For each of the two methods asked in the previous question, what is the Big-Oh complexity?

    ANSWER: a -- O(1), b -- O(n^2)

  5. Based on the O notation, approximately how many swaps and comparisons occur when SelectionSort is called on a worst-case array of length 8? Choose one that applies.
    1. 16
    2. 64
    3. 100
    4. 800

    ANSWER: b (64 <== 8^2)

  6. Based on the O notation, approximately how many swaps and comparisons occur when MergeSort is called on a worst-case array of length 8? Choose one that applies.
    1. 8
    2. 16
    3. 24
    4. 64

    ANSWER: c (24 <== 8*lg(8) == 8*3))

  7. Give the Big-Oh complexity of each of the code segment below.
    1. int sum = 0; 
      for (int i = 1; i <= n; i++) {
        int j = i;
        while (j > 0) { 
          sum += j; 
          j /= 2; 
        }
      } 
      ANSWER: O(n log n)

    2. int sum = 0; 
      int i, j; 
      for (i = 1; i <= n/2; i++) 
        sum++; 
      for (j = i; j <= n; j++) 
        sum++;
      ANSWER: O(n)
    3. int sum = 0; 
      int i = 1; j = n * n; 
      while (i++ < j--) 
        sum++;
      ANSWER: O(n^2)

  8. Using Java ArrayList, write TWO versions of a procedure which receives two ArrayList<Integer> objects, and returns true if the two lists are equal (i.e., having the same elements) or false otherwise. Two versions are:
    1. O(N2)
    2. O(N*log2(N)) 
    Assume neither list contain duplicates. 

    ANSWER:

    // version 1: O(n^2)
    public boolean areListsEqual1(ArrayList<Integer> ar1, ArrayList<Integer> ar2) {
      int len = ar1.size();
      if (len != ar2.size())
        return false;
      else {
        for (int i = 0; i < len; ++i) {
          Integer val1 = ar1.get(i);
          boolean found = false;
          for (int j = 0; j < len; ++j) {
            if (ar2.get(j).equals(val1)) {
              found = true;
              break;
            }
          }
          // if flag has remained false, no matching element was found for val1
          if (!found)
            return false; // early exit
        }
        // all elements in ar1 had a counterpart in ar2
        return true;
      }
    }
    
    // version 2: O(n log n)
    public boolean areListsEqual2(ArrayList<Integer> ar1, ArrayList<Integer> ar2) {
      int len = ar1.size();
      if (len != ar2.size())
        return false;
      else {
        // sort both arrays first
        Collections.sort(ar1);
        Collections.sort(ar2);
        
        // traverse two arrays simultaneously
        for (int i = 0; i < len; ++i) {
          if (!ar1.get(i).equals(ar2.get(i))
            return false; // early exit
        }
        // all elements matched
        return true;
      }
    } 
  9. Below is the method Bubblesort.
    void Bubblesort(int[] data) 
    {
      int tmp,i,j;
      int n = data.length;
    
      for (i=0; i<n-1; i++) {
        for (j=0; j<n-i-1; j++)
          if (data[j] > data[j+1]) {
            tmp = data[j];
            data[j] = data[j+1];
            data[j+1] = tmp;
        }
      }
    }
    1. What is the big-Oh complexity of the method? -- ANSWER: O(n^2)
    2. Show the content of an array {5, 3, 2, 4} when the method is called with the array (and its length 4 as the 2nd parameter).  Show the array for EACH i and j combination.

      ANSWER:

                +---+---+---+---+
      initially | 5 | 3 | 2 | 4 |
                +---+---+---+---+
      
                +---+---+---+---+
       i=0, j=0 | 3 | 5 | 2 | 4 |
                +---+---+---+---+
      
                +---+---+---+---+
       i=0, j=1 | 3 | 2 | 5 | 4 |
                +---+---+---+---+
      
                +---+---+---+---+
       i=0, j=2 | 3 | 2 | 4 | 5 |
                +---+---+---+---+
      
                +---+---+---+---+
       i=1, j=0 | 2 | 3 | 4 | 5 |
                +---+---+---+---+
      
                +---+---+---+---+
       i=1, j=1 | 2 | 3 | 4 | 5 |
                +---+---+---+---+
      
                +---+---+---+---+
       i=2, j=0 | 2 | 3 | 4 | 5 |
                +---+---+---+---+
  10. Write a comparator class called IgnoreCaseComp so that (Java) Strings are sorted by their lexicographical order irrespective of the case (upper/lower).
    Then write an application class which demonstrates the class.

    ANSWER:

    import java.util.Arrays;
    import java.util.Comparator;
    
    class IgnoreCaseComp implements Comparator<String>
    {
      public int compare(String s1, String s2)
      {
        return s1.toLowerCase().compareTo(s2.toLowerCase()); // or upper case
      }
    }
    
    public class ICCDemo {
      public static void main(String[] args) {
        String[] sar1 = {"abc", "ABC"};
        String[] sar2 = Arrays.copyOf(sar1, sar1.length);
    
        Arrays.sort(sar1);
        Arrays.sort(sar2, new IgnoreCaseComp());
    
        System.out.println("sar1 (with compareTo()): " + Arrays.toString(sar1));
        System.out.println("sar2 (with ignore case): " + Arrays.toString(sar2));
      }
    }
    
    /* Output of the program
    
    sar1 (with compareTo()): [ABC, abc]
    sar2 (with ignore case): [abc, ABC]
    
    */
  11. Priority Queues.
    1. For the (min-)heap below, show the result of inserting 1.

    2. ANSWER:

      (1) First place 1 at the end of the queue 
      
                           0    1    2    3    4    5    6    7    8    9    10
               5         +----+----+----+----+----+----+----+----+----+----+----+ 
             /   \       |  5 |  8 | 50 | 11 | 10 | 52 | 55 | 25 | 22 | 20 |  1 | 
           8       50    +----+----+----+----+----+----+----+----+----+----+----+  
         /   \     / \ 
        11    10  52  55 
       /  \   / \
      25  22 20  1
      
      (2) Swap 1 and 10 (because 10 > 1) 
      
                           0    1    2    3    4    5    6    7    8    9    10
               5         +----+----+----+----+----+----+----+----+----+----+----+ 
             /   \       |  5 |  8 | 50 | 11 |  1 | 52 | 55 | 25 | 22 | 20 | 10 |
           8       50    +----+----+----+----+----+----+----+----+----+----+----+
         /   \     / \ 
        11     1  52  55 
       /  \   / \
      25  22 20 10
      
      (3) Swap 1 and 8 (because 8 > 1) 
      
                           0    1    2    3    4    5    6    7    8    9    10
               5         +----+----+----+----+----+----+----+----+----+----+----+ 
             /   \       |  5 |  1 | 50 | 11 |  8 | 52 | 55 | 25 | 22 | 20 | 10 |
           1       50    +----+----+----+----+----+----+----+----+----+----+----+
         /   \     / \ 
        11     8  52  55 
       /  \   / \
      25  22 20 10
      
      (4) Swap 1 and 5 (because 5 > 1) --the final tree/queue 
      
                           0    1    2    3    4    5    6    7    8    9    10
               1         +----+----+----+----+----+----+----+----+----+----+----+ 
             /   \       |  1 |  5 | 50 | 11 |  8 | 52 | 55 | 25 | 22 | 20 | 10 |
           5       50    +----+----+----+----+----+----+----+----+----+----+----+
         /   \     / \ 
        11     8  52  55 
       /  \   / \
      25  22 20 10
    3. For the (min-)heap below, show the result of applying DeleteMin.

       

      ANSWER:

       (1) Pop the root (4) and replace it with the last element in the queue (50). 
      
                           0    1    2    3    4    5    6    7    8  
               50        +----+----+----+----+----+----+----+----+----+ 
             /    \      | 50 | 11 | 17 | 22 | 19 | 20 | 60 | 65 | 30 | 
           11      17    +----+----+----+----+----+----+----+----+----+ 
          /  \     / \ 
        22    19  20  60 
       / \   
      65  30
      
      (2) Swap 50 and 11 (because 11 < 17 and 50 > 11) 
      
                           0    1    2    3    4    5    6    7    8  
               11        +----+----+----+----+----+----+----+----+----+ 
             /    \      | 11 | 50 | 17 | 22 | 19 | 20 | 60 | 65 | 30 | 
           50      17    +----+----+----+----+----+----+----+----+----+ 
          /  \     / \ 
        22    19  20  60 
       / \   
      65  30
      
      (3) Swap 50 and 19 (because 19 < 20 and 50 > 19) --the final tree/queue 
      
                           0    1    2    3    4    5    6    7    8  
               11        +----+----+----+----+----+----+----+----+----+ 
             /    \      | 11 | 19 | 17 | 22 | 50 | 20 | 60 | 65 | 30 | 
           19      17    +----+----+----+----+----+----+----+----+----+ 
          /  \     / \ 
        22    50  20  60 
       / \   
      65  30
  12. When a heap of N elements are stored in an array, and the elements are stored from index 0 (as shown in the lecture note, NOT 1 as in the textbook), what is the index of the 'last internal node'?

    ANSWER: parent of the last leaf node, found at index (n - 1 - 1) / 2 = (n - 2) / 2

  13. Given an array [3, 1, 8, 5, 4, 7, 6], show the result of the first two iterations, plus the result of initial build-heap to make a max heap, of the Heap Sort algorithm described in the lecture note.  Draw the content of the array similar to the exercise solution.

    ANSWER:

    Initial:        [3, 1, 8, 5, 4, 7, 6] 
    
    After max-heap: [8, 5, 7, 1, 4, 3, 6]
    
    After 1st iter: [7, 5, 6, 1, 4, 3, 8]
    
    After 2nd iter: [6, 5, 3, 1, 4, 7, 8]
  14. Quick-Find. 
    [Textbook Exercise #1.5.1 (p.  235)] Show the contents of the id[] array and the number of times the array is accessed for each input pair when you use quick-find for the sequence 9-0, 3-4, 5-8, 7-2, 2-1, 5-7, 0-3, 4-2.

    ANSWER:
    Initial 
            0   1   2   3   4   5   6   7   8   9
          +---+---+---+---+---+---+---+---+---+---+
      id  | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
          +---+---+---+---+---+---+---+---+---+---+ 
    union(9,0)
          +---+---+---+---+---+---+---+---+---+---+
      id  | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 0 |
          +---+---+---+---+---+---+---+---+---+---+
    union(3,4)
          +---+---+---+---+---+---+---+---+---+---+
      id  | 0 | 1 | 2 | 4 | 4 | 5 | 6 | 7 | 8 | 0 |
          +---+---+---+---+---+---+---+---+---+---+
    union(5,8)
          +---+---+---+---+---+---+---+---+---+---+
      id  | 0 | 1 | 2 | 4 | 4 | 8 | 6 | 7 | 8 | 0 |
          +---+---+---+---+---+---+---+---+---+---+
    union(7,2)
          +---+---+---+---+---+---+---+---+---+---+
      id  | 0 | 1 | 2 | 4 | 4 | 8 | 6 | 2 | 8 | 0 |
          +---+---+---+---+---+---+---+---+---+---+ 
    union(2,1)
            0   1   2   3   4   5   6   7   8   9
          +---+---+---+---+---+---+---+---+---+---+
      id  | 0 | 1 | 1 | 4 | 4 | 8 | 6 | 1 | 8 | 0 |
          +---+---+---+---+---+---+---+---+---+---+
    union(5,7)
          +---+---+---+---+---+---+---+---+---+---+
      id  | 0 | 1 | 1 | 4 | 4 | 1 | 6 | 1 | 1 | 0 |
          +---+---+---+---+---+---+---+---+---+---+
    union(0,3)
          +---+---+---+---+---+---+---+---+---+---+
      id  | 4 | 1 | 1 | 4 | 4 | 1 | 6 | 1 | 1 | 4 |
          +---+---+---+---+---+---+---+---+---+---+
    union(4,2)
          +---+---+---+---+---+---+---+---+---+---+
      id  | 1 | 1 | 1 | 1 | 1 | 1 | 6 | 1 | 1 | 1 |
          +---+---+---+---+---+---+---+---+---+---+

  15. Quick-Union.
    [Textbook Exercise #1.5.2 (p.  235)] Do the previous question, but use quick-union.  In addition, draw the forest of trees represented by the ad[] array after each input pair is processed.

    ANSWER:
    Initial 
            0   1   2   3   4   5   6   7   8   9
          +---+---+---+---+---+---+---+---+---+---+
      id  | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
          +---+---+---+---+---+---+---+---+---+---+ 
    union(9,0)
          +---+---+---+---+---+---+---+---+---+---+
      id  | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 0 |
          +---+---+---+---+---+---+---+---+---+---+
    union(3,4)
          +---+---+---+---+---+---+---+---+---+---+
      id  | 0 | 1 | 2 | 4 | 4 | 5 | 6 | 7 | 8 | 0 |
          +---+---+---+---+---+---+---+---+---+---+
    union(5,8)
          +---+---+---+---+---+---+---+---+---+---+
      id  | 0 | 1 | 2 | 4 | 4 | 8 | 6 | 7 | 8 | 0 |
          +---+---+---+---+---+---+---+---+---+---+
    union(7,2)
          +---+---+---+---+---+---+---+---+---+---+
      id  | 0 | 1 | 2 | 4 | 4 | 8 | 6 | 2 | 8 | 0 |
          +---+---+---+---+---+---+---+---+---+---+ 
    union(2,1)
            0   1   2   3   4   5   6   7   8   9
          +---+---+---+---+---+---+---+---+---+---+
      id  | 0 | 1 | 1 | 4 | 4 | 8 | 6 | 2 | 8 | 0 |
          +---+---+---+---+---+---+---+---+---+---+
    union(5,7)
          +---+---+---+---+---+---+---+---+---+---+
      id  | 0 | 1 | 1 | 4 | 4 | 8 | 6 | 2 | 1 | 0 |
          +---+---+---+---+---+---+---+---+---+---+
    union(0,3)
          +---+---+---+---+---+---+---+---+---+---+
      id  | 4 | 1 | 1 | 4 | 4 | 8 | 6 | 2 | 1 | 0 |
          +---+---+---+---+---+---+---+---+---+---+
    union(4,2)
          +---+---+---+---+---+---+---+---+---+---+
      id  | 4 | 1 | 1 | 4 | 1 | 8 | 6 | 2 | 1 | 0 |
          +---+---+---+---+---+---+---+---+---+---+

            1        6
        /   |   \  
       2    4    8
       |   / \   |
       7  0   3  5
          |
          9
  16. Explain which of the data structures that we have discussed during this quarter would be most useful in each of the following applications. You may choose from the following data structures: stack, queue, list, or priority queue.
    1. You are building a system which processes orders that have been placed in an on-line store. The orders should be processed in the order that they were made.
      ANSWER: (FIFO) queue
    2. You are writing a text editor, and wish to implement an "undo" feature, which behaves that way that the Control-z keystroke does in Microsoft Word.
      ANSWER: stack
    3. You are building a system that maintains a wait-list of passengers on a flight who are waiting for an upgrade to first class. The passenger with the most frequent flier miles is the first to be upgraded when a first class seat becomes available.
      ANSWER: priority queue
    4. You are building a system that will be used to maintain a list of people who are employed by a company. The system should maintain the list in alphabetical order by the employees' last names, and should support operations to add and remove employees from the list as they are hired by or leave the company.
      ANSWER: list