Recurrence Relations As you arrive: Get out a piece of paper and and pen. We’re gonna do some math in class today and you’d want to follow along. Put your name at the top. After class today… • You will be able to explain the derivation of 2 example recurrence relations • You will be able to use recurrence relations to compute the big-O of recursive functions Warm Up public void whatIsMyBigO(String[] strings) { int current = 0; while(strings[current].equals("ninja")) { current++; //this loop will eventually end because //I know there is at least one non-ninja //string in the list } } 1. 2. 3. 4. 5. O(n) O(n log n) O(1) O(n2) O(log n) Warm Up: Harder //finds an element in a sorted array public int mikeSearch(int[] sorted, int first, int upto, int key) { while (first < upto) { int mid = (first + upto) / 2; // Compute mid point. if (key < sorted[mid]) { upto = mid; // repeat search in bottom half. } else if (key > sorted[mid]) { first = mid + 1; // Repeat search in top half. } else { return mid; // Found it. return position } } return -(first + 1); // Failed to find key } 1. 2. 3. 4. 5. O(n) O(n log n) O(1) O(n2) O(log n) The problem private boolean containsNodeBST(int value, MikesIntTreeNode current) { if(current == null) return false; if(current.value == value) return true; if(value < current.value) { return containsNode(value, current.left); } else { return containsNode(value, current.right); } } What is the Big O assuming the Binary Search Tree is height balanced? What is the Big O not assuming the Binary Search Tree is height balanced? A. B. C. D. E. Priority Queue • You add to it like a normal queue • But when you remove, it gets removed in order of size (smallest first) PriorityQueue<String> ex = new PriorityQueue<String>(); ex.add("hello"); ex.add("cs100"); ex.add("class"); while(!ex.isEmpty()) { System.out.println(ex.remove()); } // Prints: // class // cs100 // hello Priority Queue What does this print out? PriorityQueue<Integer> ex = new PriorityQueue<Integer>(); ex.add(2); ex.add(13); ex.add(9); ex.add(75); ex.add(4); while(!ex.isEmpty()) { System.out.println(ex.remove()); } Priority Queue Problem • Snarf the code • Imagine we’ve got a class BestPrice, that tracks the best price of an item we’re looking to buy. Everytime we find a new price we call add to add the price we’re looking for. Then when someone calls buyCheapest(n) we buy n items, using the cheapest offer we have then the second cheapest, etc. We return the total cost to buy n items. • Take a look at the sample code in main if this in unclear. • Hint: make 1 instance variable – a priority queue