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
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
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