Chapter 4
I
Quicksort
problems. D&C is another tool in your toolbox. When you get a new
problem, you don’t have to be stumped. Instead, you can ask, “Can I
solve this if I use divide and conquer?”
At the end of the chapter, you’ll learn your first major D&C algorithm:
quicksort
. Quicksort is a sorting algorithm, and a much faster one than
selection sort (which you learned in chapter 2). It’s a good example of
elegant code.
Divide & conquer
D&C can take some time to grasp. So, we’ll do three
examples. First I’ll show you a visual example. Then
I’ll do a code example that is less pretty but maybe
easier. Finally, we’ll go through quicksort, a sorting
algorithm that uses D&C.
Suppose you’re a farmer with a plot of land.
You want to divide this farm evenly into
square
plots. You want the plots
to be as big as possible. So none of these will work.
53
Divide & conquer
How do you figure out the largest square size you can use for a plot of
land? Use the D&C strategy! D&C algorithms are recursive algorithms.
To solve a problem using D&C, there are two steps:
1. Figure out the base case. This should be the simplest possible case.
2. Divide or decrease your problem until it becomes the base case.
Let’s use D&C to find the solution to this problem. What is the largest
square size you can use?
First, figure out the base case. The easiest case would be if one side was
a multiple of the other side.
Suppose one side is 25 meters (m) and the other side is 50 m. Then the
largest box you can use is 25 m × 25 m. You need two of those boxes to
divide up the land.
Now you need to figure out the recursive case. This is where D&C
comes in. According to D&C, with every recursive call, you have to
reduce your problem. How do you reduce the problem here? Let’s start
by marking out the biggest boxes you can use.
|