https://slides.com/georgelee/ics141-recursive-algorithms/live
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
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)
How would you draw a target symbol?
Find the sum of the numbers in a list
The Fibonacci Sequence
Find n!
Find an
Linear search
Binary search
Both algorithms follow the same pattern. Split the array into two halves, sort them, and then join them together.
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.
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)
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).
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.