100 likes | 246 Views
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
E N D
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 publicvoidwhatIsMyBigO(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 } } O(n) O(n log n) O(1) O(n2) O(log n)
Warm Up: Harder //finds an element in a sorted array publicintmikeSearch(int[] sorted, int first, intupto, int key) { while (first < upto) { int mid = (first + upto) / 2; // Compute mid point. if (key < sorted[mid]) { upto = mid; // repeat search in bottom half. } elseif (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 } O(n) O(n log n) O(1) O(n2) O(log n)
The problem privatebooleancontainsNodeBST(int value, MikesIntTreeNode current) { if(current == null) returnfalse; if(current.value == value) returntrue; if(value < current.value) { returncontainsNode(value, current.left); } else { returncontainsNode(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 = newPriorityQueue<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 = newPriorityQueue<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