Docsity

Divide and Conquer Algorithms: Mergesort and Quicksort - Prof. Edward Bosworth, Study notes of Computer Science

Toggle sidebar
bg1
Chapter 4: Divide and Conquer
The name “Divide and Conquer” is an interesting title applied to a specific design strategy
that often leads to very efficient algorithms. Many of the better search and sort algorithms
are based on the divide and conquer strategy. Algorithms designed according to this strategy
have the following characteristics:
1) A problem’s instance is divided into several smaller instances of the same problem.
The strategy usually works best when the smaller instances are all of approximately
the same size; thus a divide-and-conquer sort strategy applied to a list of N items
might break the problem instance into two instances, each of size about N/2.
2) The smaller instances are solved in the same manner, except that there is always a
size at which another algorithm can be considered to be applied. For example, many
sort algorithms designed with this strategy break down the problem instances into
instances of size one, which automatically are considered sorted.
3) The algorithm usually has a mechanism for combining the solutions of the smaller
problem instances into the solution of a given instance.
4) The algorithms designed according to the divide-and-conquer strategy are often
often implemented with recursion, but this is not necessary.
There is a convention often used in the illustration of these algorithms. When the algorithm
functions by producing two smaller instances of size N/2, it is common practice to use
problem instances of size N = 2K, K > 1, as examples. This is done for convenience only.
As the book notes, the mere fact that one can produce a divide-and-conquer solution to a
problem does not imply that the strategy produces superior results. Consider the problem of
adding a list of N integers, which I denote by A1, A2, ... , AN. It should be obvious that the
following algorithm solves the problem.
Function Add (A[1 .. N]) // Note the 1-based array
It N > 1 Then
S1 = Add (A[1 .. N/2]
S2 = Add (A [(N/2 + 1) .. N]
Return (S1 + S2)
Else
Return A[1]
We shall first analyze this algorithm both by example and by the Master Theorem, then
consider a minor variant of the algorithm, which will introduce an interesting design
question. But first, a sample data set – as promised the size being a power of 2.
Page 1 of 13 CPSC 5115 Last Revised November 28, 2020
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Partial preview of the text

Download Divide and Conquer Algorithms: Mergesort and Quicksort - Prof. Edward Bosworth and more Study notes Computer Science in PDF only on Docsity!

Chapter 4: Divide and Conquer

The name “Divide and Conquer” is an interesting title applied to a specific design strategy that often leads to very efficient algorithms. Many of the better search and sort algorithms are based on the divide and conquer strategy. Algorithms designed according to this strategy have the following characteristics:

  1. A problem’s instance is divided into several smaller instances of the same problem. The strategy usually works best when the smaller instances are all of approximately the same size; thus a divide-and-conquer sort strategy applied to a list of N items might break the problem instance into two instances, each of size about N/2.
  2. The smaller instances are solved in the same manner, except that there is always a size at which another algorithm can be considered to be applied. For example, many sort algorithms designed with this strategy break down the problem instances into instances of size one, which automatically are considered sorted.
  3. The algorithm usually has a mechanism for combining the solutions of the smaller problem instances into the solution of a given instance.
  4. The algorithms designed according to the divide-and-conquer strategy are often often implemented with recursion, but this is not necessary. There is a convention often used in the illustration of these algorithms. When the algorithm functions by producing two smaller instances of size N/2, it is common practice to use problem instances of size N = 2K, K > 1, as examples. This is done for convenience only. As the book notes, the mere fact that one can produce a divide-and-conquer solution to a problem does not imply that the strategy produces superior results. Consider the problem of adding a list of N integers, which I denote by A 1 , A 2 , ... , AN. It should be obvious that the following algorithm solves the problem. Function Add (A[1 .. N]) // Note the 1-based array It N > 1 Then S1 = Add (A[1 .. N/2] S2 = Add (A [(N/2 + 1) .. N] Return (S1 + S2) Else Return A[1] We shall first analyze this algorithm both by example and by the Master Theorem, then consider a minor variant of the algorithm, which will introduce an interesting design question. But first, a sample data set – as promised the size being a power of 2. Page 1 of 13 CPSC 5115 Last Revised November 28, 2020

Consider adding the numbers 91, 54, 75, 67, 79, 84, 83, 58. Apply the algorithm. Note that we underline the sums produced. 91, 54, 75, 67 | 79, 84, 83, 58 91, 54 | 75, 67 | 79, 84, 83, 58 91 , 54 | 75, 67 | 79, 84, 83, 58 145 | 75, 67 | 79, 84, 83, 58 145 | 75 , 67 | 79, 84, 83, 58 145 | 142 | 79, 84, 83, 58 287 | 79, 84, 83, 58 287 | 79, 84 | 83, 58 287 | 79 , 84 | 83, 58 287 | 163 | 83, 58 287 | 163 | 83 , 58 287 | 163 | 141 287 | 304 591 Let’s apply the master theorem to the algorithm. T(N) = 2T(N/2) + 1 T(1) = 1 In terms of the Master Theorem, we have A = 2, B = 2, and F(N) = 1 = N^0 , so that F(N)  (N^0 ) and D = 0. BD^ = 2^0 = 1, and A > BD, so we compute logB(A) = log 2 (2) = 1, and get T(N)  (N^1 ). This is no big improvement over the standard algorithm, which requires exactly (N – 1) additions to add a list of N numbers. As a diversion, consider the following variant of the recursive addition algorithm. We observe that the smallest problem instance will either have size 1 or size 2 (N = 1 or N = 2), and that we are wasting time invoking the addition of a single item to get itself. We shall return to this variant of the design strategy when we consider other algorithms, but note now that there is no particular reason to favor or disfavor it. Function Add (A[1 .. N]) // Note the 1-based array It N > 2 Then S1 = Add (A[1 .. N/2] S2 = Add (A [(N/2 + 1) .. N] Return (S1 + S2) Else If (N = 2) Then Return A[1] + A[2] Else Return A[1]

Mergesort We now arrive at the mergesort algorithm. As the book notes, this is a classic example of application of the divide and conquer design strategy. An array of N elements is divided into two arrays of N/2 elements, each sub-array is sorted, and the two sorted sub-arrays are merged. The best presentation of this algorithm is as a recursive procedure. In the following algorithm, we use the floor and ceiling functions, which we define by example. Let N be 7. Then N/2 = 3.5, a real number, and 3.5 = 3, and 3.5 = 4. For any N, we have N/2 + N/2 = N. Note that we also revert to the book’s use of 0-based arrays. Algorithm Mergesort ( A[0 .. (N – 1)] ) // // Input: An array A[0 .. (N – 1)] of sortable elements // Output: The array sorted in non-decreasing order // Work arrays: Two arrays of size N/2. // If (N > 1) Then Copy A[0 .. N/2 – 1] to B[0 .. (N/2 – 1)] Copy A[N/2 .. (N – 1)] to C[0 .. (N/2 – 1)] Mergesort (B[0 .. (N/2 – 1)]) Mergesort (C[0 .. (N/2 – 1)]) Merge (B, C, A) // Merge B and C to give A // // Else do nothing – array of 1 element must be sorted. End If Inspection of this algorithm shows that it is the merge algorithm that does the “heavy lifting”. We present a straightforward implementation of a two-way merge algorithm, which can be extended to an N-way algorithm with very little thought. Note that the merge algorithm uses at most N comparisons to merge two arrays with combined element count of N. Thus merge is a linear-time algorithm. The algorithm below is slightly different from that on page 124 of the textbook in its handling of what happens when one of the input arrays has been completely processed. At that time, the merge algorithm just copies the contents of the other array into the output. The double-while loops at the end of this next algorithm are a classic approach to this issue.

Algorithm Merge(B[0..(P – 1)], C[0..(Q-1)], A[0..(P + Q – 1)]) I = 0; J = 0; K = 0 // Initialize some indices While ( (I < P) And (J < Q) ) Do If B[I] < C[J] Then A[K] = B[I] I = I + 1 Else A[K] = C[J] J = J + 1 End If // Always increment K – the index into A. K = K + 1 End Do // At most one of the following loops will execute. While (I < P) Do A[K] = B[I] I = I + 1 K = K + 1 End Do While (J < Q) Do A[K] = C[J] J = J + 1 K = K + 1 End Do Again, let’s apply the Master theorem to this. The recurrence equation is T(N) = 2T(N/2) + N the Merge part taking N steps. Using the Master theorem with T(N) = AT(N/B) + F(N), we see that A = 2, B = 2, and that F(N) = N  (N^1 ) and D = 1. BD^ = 2^1 = 2, so A = BD, and we have T(N)  (NDlog(N)) T(N)  (Nlog(N)) In a moment, we shall investigate quicksort, another (Nlog(N)) sorting algorithm and argue that it is, on average a bit faster, than mergesort. However, it is provable that any algorithm that sorts by comparison only must be (Nlog(N)), so this is as good as it gets.

We now examine the operation of the algorithm on the list 3, 1, 4, 1, 5, 9, 2, 6, 5, 3. The first split divides the list into two sub-lists, each of size 5. The sub-lists of size 5 are each divided into lists of size 2 and 3, etc. 3, 1, 4, 1, 5, 9, 2, 6, 5, 3 Split 3, 1, 4, 1, 5 || 9, 2, 6, 5, 3 More splits 3, 1 | 4, 1, 5 || 9, 2 | 6, 5, 3 Another split 3, 1 | 4 | 1, 5 || 9, 2 | 6 | 5, 3 Merge 1, 3 | 4 | 1, 5 || 9, 2 | 6 | 3, 5 Merge 1, 3 | 1, 4, 5 || 9, 2 | 3, 5, 6 Merge 1, 1, 3, 4, 5 || 2, 3, 5, 6, 9 Final Merge 1, 1, 2, 3, 3, 4, 5, 5, 6, 9 Two Approaches to Splitting Arrays We have been considering the application of the divide and conquer strategy as a basis for algorithms to sort arrays. To nobody’s surprise, we have been splitting arrays into two parts. There are two obvious strategies. The first, used by mergesort, is to divide the array arbitrarily in half. The array A[1 to N] is divided into A[1 to N/2] and A[N/2 to N]. Another approach would be to pick a pivot value AP, with a value ideally close to the average value of the values in the array. We then divide the array into two parts Items with value greater than AP, and items with value not greater than AP. Consider the division of the array A[1 to N] split by pivot value AP into two sub-arrays L an array of all items of value  AP. R an array of all items of value > AP. If the pivot value is well chosen, the arrays L and R will be of about the same size. The next sort algorithm we shall study, called quicksort , applies this pivot value strategy to split the arrays. We shall see that there are a number of strategies designed to pick a good pivot value. The problem is that the simple and efficient strategies can occasionally pick a very poor pivot value for an array, while those strategies that can be guaranteed to pick a good pivot value are so complex that they slow the sort algorithm excessively.

Quicksort This is a standard sort algorithm developed by C.A.R. Hoare. If you have any trouble recalling the name of the developer, just think of “quickie”. At the top level, the quicksort algorithm has a standard description. Algorithm Quicksort (A [L..R] ) // // Sorts an array using the quicksort algorithm // Input: A subarray A[L..R] of A[0..(N-1)], defined by its // left and right indices L and R, with L  R. // Output: The subarray A[L..R] sorted in nondecreasing order. // If (L < R) Then S = Partition(A[L..R]) // S is a split position, so Quicksort(A[L..(S-1)]) // element A[S] is in its correct Quicksort(A[(S+1)..R]) // position. End If The variations in the modifications of quicksort are always found in the partition algorithm. We shall study one of the more common varieties of the partition algorithm. The student should be aware that there are quite a few variants of partition. The reasons are quite simple:

  1. A more sophisticated partition algorithm makes the quicksort less likely to display the poor performance found in the worst cases.
  2. A more sophisticated partition algorithm takes more time and thus slows the execution of the quicksort. Basically the question is how much we want to penalize the average performance of the algorithm to guard against bad performance in the worst case. Most people have decided to select a rather simple, but efficient, partition algorithm. The basic strategy of all partition algorithms is simply stated. Given a subarray A[L..R], with R > L, and a pivot element P, rearrange the subarray into three parts:
  3. First only elements that are less than or equal to P, then
  4. The pivot element P, then
  5. Only elements that are greater than or equal to P. There are a number of strategies for selecting the pivot element from the subarray A[L..R]. The simplest method is to pick the first element: P = A[L]. There are other methods with supposed advantages. Here is one. Compute index M = (L + R) / 2 Examine three values A[L], A[M], and A[R] Use the middle value as the pivot. If A[L] < A[R] < A[M], then P = A[R]. There are also several ways to partition the subarray given the value of the pivot element. The book discusses one of the more popular ways based on two scans. The student is invited to read the book for the justification of this approach. We give the algorithm and then show a sample partition in order to illustrate it.

Now we examine a more typical problem instance with 10 elements to be partitioned. Note that the fact that J = R + 1 does not imply the existence of an array element with that index. P = A[L] = 3 I = L J = R + 1 Loop A begins. Loop B begins and continues until the index I is set as follows L I R J 3 1 4 1 5 9 2 6 5 4 Loop C begins and continues until the index J is set as follows L I J R 3 1 4 1 5 9 2 6 5 4 Swap A[I] and A[J] L I J R 3 1 2 1 5 9 4 6 5 4 End of Loop A J = I + 4 so we go again. Loop A begins again Loop B begins and continues until the index I is set as follows. L I J R 3 1 2 1 5 9 4 6 5 4 Loop C begins and continues until index J is set as follows. Note that J < I. L J I R 3 1 2 1 5 9 4 6 5 4 Swap A[I] and A[J] L J I R 3 1 2 5 1 9 4 6 5 4 End of Loop A. Note that I > J, so loop A terminates. Now swap A[I] and A[J] again to undo the last swap, to get L J I R 3 1 2 1 5 9 4 6 5 4 Finally swap A[L] and A[J] to get the partitioned array L J I R 1 1 2 3 5 9 4 6 5 4

I = L R J

Binary Search Binary search is an efficient algorithm designed to search a sorted array. Consider a subarray A[L..R], with L  R, that is in strictly non-decreasing order so that I < J implies A[I]  A[J]. Let M = (L + R)/2. The basic observation is that a search for a key K will have one of three possible outcomes.

  1. K = A[M] the element has been found
  2. K < A[M] the element, if present, will be found in A[L..(M – 1)]
  3. K > A[M] the element, if present, will be found in A[(M + 1)..R] Note that binary search is not strictly an application of the divide and conquer strategy, which calls for breaking a problem into a number of smaller problems and solving each smaller problem. In binary search, we break the problem into two smaller subproblems, but solve only one of the subproblems. This observation leads to the recurrence for the time complexity of the algorithm. T(N) = T(N/2) + 1 It is easily shown by the Master Theorem that T(N)  (log N). There are two variants of the binary search algorithms – the iterative version and recursive version. We shall present both versions, beginning with the iterative version in the book. Algorithm BinarySearch (A[0..(N – 1)], K) // // Input: An array A[0..(N – 1)] with N > 0, sorted in // non-decreasing order and a search key K. // Output: An index of an array element equal to K, or // - 1 if there is no matching element. // L = 0 R = N – 1 While L  R Do M = (L + R)/2 If (K = A[M]) Then Return M Else If (K < A[M}) Then R = M – 1 Else L = M + 1 End While Return – 1 // Indicates failure We make a few comments on this version, then move on to the recursive version.
  4. One could change the last line to read Return – M and indicate a place in the array where the key should be, if it were to be inserted.
  5. This is one of the few places where an obsolete FORTRAN construct would work very well. We would write If (K – A(M)) 10, 20, 30 to indicate the actions to be taken for K < A(M), K = A(M), and K > A(M) respectively.

We illustrate the algorithm with a very simple function F(X) = X – 3.25, with X1 = 0.0, X2 = 4.0, and EPS not specified. Note that we pick a function for which we can easily compute the zeroes directly. Here the function has a single zero at X = 3.25. Begin the algorithm XL = 0.0, and YL = – 3. XH = 4.0, and YH = 0. Having the correct initial conditions, we start the repeat loop. XL = 0.0 and XH = 4. XM = (0.0 + 4.0)/2.0 = 2. YM = 2.0 – 3.25 = – 1. YM < 0.0, so XL = XM = 2. XL = 2.0 and XH = 4. XM = (2.0 + 4.0)/2.0 = 3. YM = 3.0 – 3.25 = – 0. YM < 0.0, so XL = XM = 3. XL = 3.0 and XH = 4. XM = (3.0 + 4.0)/2.0 = 3. YM = 3.5 – 3.25 = 0. YM > 0.0, so XH = XM = 3. XL = 3.0 and XH = 3. XM = (3.0 + 3.5)/2.0 = 3. YM = 3.25 – 3.25 = 0. YM = 0.0, so return XM = 3.25 as the answer.