35 Algorithm Types
35 Algorithm Types
Algorithm classification
Algorithms that use a similar problem-solving approach can be grouped together This classification scheme is neither exhaustive nor disjoint The purpose is not to be able to classify an algorithm as one type or another, but to highlight the various ways in which a problem can be attacked
I call these simple because several of the other algorithm types are inherently recursive
Backtracking algorithms
Backtracking algorithms are based on a depth-first recursive search A backtracking algorithm:
Tests to see if a solution has been found, and if so, returns it; otherwise For each choice that can be made at this point, Make that choice Recur If the recursion returns a solution, return it If no choices remain, return failure
Traditionally, an algorithm is only called divide and conquer if it contains two or more recursive calls
Examples
Quicksort:
Partition the array into two parts, and quicksort each of the parts No additional work is required to combine the two sorted parts
Mergesort:
Cut the array in half, and mergesort each half Combine the two sorted arrays into a single sorted array by merging them
This is not a divide and conquer algorithm because, although there are two recursive calls, only one is used at each level of the recursion
Fibonacci numbers
To find the nth Fibonacci number:
If n is zero or one, return one; otherwise, Compute fibonacci(n-1) and fibonacci(n-2) Return the sum of these two numbers
This differs from Divide and Conquer, where subproblems generally need not overlap
Since finding the nth Fibonacci number involves finding all smaller Fibonacci numbers, the second recursive call has little work to do The table may be preserved and used again later
Greedy algorithms
An optimization problem is one in which you want to find, not just a solution, but the best solution A greedy algorithm sometimes works well for optimization problems A greedy algorithm works in phases: At each phase:
You take the best you can get right now, without regard for future consequences You hope that by choosing a local optimum at each step, you will end up at a global optimum
For US money, the greedy algorithm always gives the optimum solution
A better solution would be to use two 7 kron pieces and one 1 kron piece
This only requires three coins
Randomized algorithms
A randomized algorithm uses a random number at least once during the computation to make a decision
Example: In Quicksort, using a random number to choose a pivot Example: Trying to factor a large prime by choosing random numbers as possible divisors
The End