Applications of Recurrences Section 8 1 Sample Problem
Applications of Recurrences Section 8. 1
Sample Problem • Suppose a colony of bacteria doubles in number every hour. Write a recurrence formula for the number of bacteria after n hours. • Solution: an = 2 an-1 • How many bacteria are there after 5 hours if there were 5 bacteria to start with? • Solution: a 5 = 2 a 4 = 22 a 3 = 23 a 2 = 24 a 1 = 25 a 0 = 255 = 160
Iterating a Recurrence • We can find a formula for most recurrences by iterating them • Like what we just did, except we’ll use n instead of 5
The Towers of Hanoi • Some Vietnamese have 64 disks of different sizes, stacked in decreasing size on one of three pegs. • They must move the disks from Peg 1 to Peg 3 move using Peg 2. A larger disk may not be placed on a smaller one. • After the transfer, the world will end. : -) • How long will it take to finish the task? • Count the number of moves.
Finding the Recurrence • Moving n disks from Peg 1 to Peg 3 can be accomplished by: • moving n-1 disks to Peg 2 • moving the bottom disk to Peg 3 • moving the n-1 disks from Peg 2 to Peg 3. • Hn = 2 Hn-1 + 1 • H 1 = 1 • See hanoi 1. cpp, hanoi 2. cpp
Iterating the Recurrence When will this stop?
Finishing the Iteration
A Bitstring Example • How many bitstrings of length n do not have consecutive 0’s? Find a recurrence relation. • Note: • • a 0 = 1 (the empty string) a 1 = 2 (0 and 1) a 2 = 3 (01, 10, and 11) a 3 = 5 (010, 011, 101, 110, 111) • Consider such a bitstring • Either it ends with a 1 or a 0.
We won’t learn how to solve this type of recurrence!
“Divide-and-Conquer” Recurrences Section 8. 3
Divide and Conquer • Divide-and-Conquer algorithms break a problems into much smaller parts • typical half the size of the original • Examples: • • Binary Search Merge Sort Quick Sort Many others
Binary Search Redux • Recall Algorithm 3, Section 3. 1 • When the size of the list is 1, the while loop comparison fails • then there is one more check to see if the item was found • so a 1 = 2 • Otherwise, there is another comparison inside the loop, and the size of the list is cut by half • an = an/2 + 2
Iterating Binary Search
Min. Max Problem • Find the maximum and minimum of a sequence simultaneously • You did this iteratively in a previous homework • Recursive version: • • Split the list in 2 Recursively solve the two parts Return the smaller of the mins and the larger of the maxes Stopping condition: when n=1, the element is both the min and max • See minmax. cpp (Look Ma, no loops!)
The Min. Max Recurrence
Merge Sort • • Divide the list in half Recursively sort each half Merge the sorted halves together Stopping condition: • A singleton list is already “sorted”; just return it • Pseudocode: • mergesort(list): if list. length = 1 return list merge(mergesort(left_half), mergesort(right_half)) • merge uses n-1 comparisons • we’ll use n in the recurrence for simplicity (since we seek O())
The Merge Sort Recurrence
- Slides: 18