Programming Problems Using Recursion 227
have been sorted. This occurs when each part has only one element or no element at all.
How does the algorithm divide the array into three parts? One solution uses these steps:
1. Determine the value of the pivot. In this example, the pivot is the first element.
2. Iterate through the original array from left (smaller indexes) to right (larger indexes)
using two indexes called low and high. The initial value of low is one higher than the
index of the pivot. The initial value of high is the largest index of the range being
considered.
3. From the left side, if an element is smaller than the pivot, low increments. If an
element is greater than the pivot, stop changing low.
4. From the right side, if an element is greater than the pivot, high decrements. If an
element is smaller than the pivot, stop changing high.
5. Now swap the elements whose indexes are low and high.
6. Continue steps 2 to 4 until low is greater than high.
7. Put the pivot between the two parts.
Note that by the last step, the array will be ordered such that all of the elements smaller
than the pivot are together, and all of the elements larger than pivot are also together. When
the pivot is placed, it is in the correct position for the final sorted array. The following figure
illustrates the procedure. The pivot is 19, low is 1, and high is 11.
index 0 1 2 3 4 5 6 7 8 9 10 11
value 19 7 12 23 8 31 6 42 28 16 51 33
variable pivot low high
Because 7 is smaller than 19, low increments.
index 0 1 2 3 4 5 6 7 8 9 10 11
value 19 7 12 23 8 31 6 42 28 16 51 33
variable pivot low high
The next value, 12, is also smaller than 19, and low increments again. The next value
is 23 and it is greater than 19. Thus, low stops incrementing.
index 0 1 2 3 4 5 6 7 8 9 10 11
value 19 7 12 23 8 31 6 42 28 16 51 33
variable pivot low high
Following the algorithm, if the value whose index is high is greater than the pivot, then
decrement high. Since 33 is greater than 19, we must decrement high.
index 0 1 2 3 4 5 6 7 8 9 10 11
value 19 7 12 23 8 31 6 42 28 16 51 33
variable pivot low high
Since 51 is also greater than 19, high decrements again.
index 0 1 2 3 4 5 6 7 8 9 10 11
value 19 7 12 23 8 31 6 42 28 16 51 33
variable pivot low high
At this moment, the value whose index is low is greater than the pivot. The value whose
index is high is smaller than the pivot. Now we swap these two values.
index 0 1 2 3 4 5 6 7 8 9 10 11
value 19 7 12 16 8 31 6 42 28 23 51 33
variable pivot low high