Recursive Algorithms
https://slides.com/georgelee/ics141-recursive-algorithms/live
Thinking Recursively
Reducing to Subproblems
Consider the Euclidean algorithm for finding the greatest common divisor of two numbers.
gcd(a, b) = gcd(b mod a, a) where b > a
gcd(0, a) = a
Definition
An algorithm is called recursive if it solves a problem by reducing it to an instance of the same problem with smaller input.
There are two parts to a recursive algorithm:
Base case: The smallest possible subproblem
Recursive case: Break down the large problem into subproblem(s)
Example
How would you draw a target symbol?
Examples
Basic Recursive Algorithms
Find the sum of the numbers in a list
The Fibonacci Sequence
Find n!
Find an
Recursive Search
Linear search
Binary search
Recursive Sorting
Merge/Quick Sort
Both algorithms follow the same pattern. Split the array into two halves, sort them, and then join them together.
Merge Sort
Split the array in half. Merge sort each of the halves. Then, merge the two halves together.
Much of the work is merging the two halves together.
Quick Sort
Select a "pivot".
Partition the array into two halves, one where all the numbers are less than (or equal) the pivot and one where all the numbers are greater than the pivot.
Sort the two parts of the partition.
Join them together (left -> pivot -> right)
Quick Sort
Downsides
Merge Sort: Typically requires additional memory when merging the two halves together.
Quick Sort: If we have a bad pivot, the algorithm is O(n2).
Towers of Hanoi
How Do We Solve This?
If we only have one disk, then it's easy. We move the disk to the end.
If we have n disks, move n - 1 disks from the start to the temporary pole using the destination as temporary
Then, move the bottom disk to the destination
Finally, move n - 1 disks from temporary to destination.
Recursive Algorithms
By George Lee
Recursive Algorithms
- 853