Docsity

Mergesort and A Linear Merge Algorithm - Lecture Notes | COP 3503, Study notes of Computer Science

Toggle sidebar
bg1
COP 3503 – Computer Science II – CLASS NOTES - DAY #11
Mergesort
The mergesort sorting algorithm uses the divide and conquer strategy in which the
original problem is split into two half-size, recursively solved problems. If the
overhead of the base case was linear [O(N)] then the overall running time of the
algorithm was O(N log2 N). The mergesort is such an algorithm and is commonly
employed for external sorting. The mergesort algorithm is a recursive,
subquadratic algorithm as follows:
1. if the number of items to sort is 0 or 1, return.
2. recursively sort the first and second halves separately.
3. merge the two sorted halves into a single sorted group.
Since this algorithm uses the divide and conquer strategy and employs the halving
principle, we know that the sorting is done in O(log2N) and thus we need only to
show that merging two sorted groups into a single sorted group can be performed
in linear time to prove the running time is O(N log2 N).
A linear merge algorithm
A linear merge algorithm requires three separate arrays A, B, and C (two input and
one output) plus an index counter per array (actr, bctr, and cctr). The index
counters are initially set to the first position in each of their arrays with
incrementation as follows:
if A[actr] < B[bctr]
C[cctr] = A[actr];
cctr++;
actr++;
} else {
C[cctr] = B[bctr];
cctr++;
bctr++;
}
Day 11 - 1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14

Partial preview of the text

Download Mergesort and A Linear Merge Algorithm - Lecture Notes | COP 3503 and more Study notes Computer Science in PDF only on Docsity!

COP 3503 – Computer Science II – CLASS NOTES - DAY # Mergesort The mergesort sorting algorithm uses the divide and conquer strategy in which the original problem is split into two half-size, recursively solved problems. If the overhead of the base case was linear [O(N)] then the overall running time of the algorithm was O(N log 2 N). The mergesort is such an algorithm and is commonly employed for external sorting. The mergesort algorithm is a recursive, subquadratic algorithm as follows:

  1. if the number of items to sort is 0 or 1, return.
  2. recursively sort the first and second halves separately.
  3. merge the two sorted halves into a single sorted group. Since this algorithm uses the divide and conquer strategy and employs the halving principle, we know that the sorting is done in O(log 2 N) and thus we need only to show that merging two sorted groups into a single sorted group can be performed in linear time to prove the running time is O(N log 2 N). A linear merge algorithm A linear merge algorithm requires three separate arrays A, B, and C (two input and one output) plus an index counter per array (actr, bctr, and cctr). The index counters are initially set to the first position in each of their arrays with incrementation as follows: if A[actr] < B[bctr] C[cctr] = A[actr]; cctr++; actr++; } else { C[cctr] = B[bctr]; cctr++; bctr++; }

Example: Linear Merge A B C actr bctr cctr

elements, and N time units are required to partition a set containing N elements. Then if N > 1 we have: T(N) = T(N-1) + N This means that the time required to quicksort N elements is equal to the time required to recursively sort the N-1 elements in the Right subset plus the time required to partition the N elements. By telescoping the equation above we have: T(N) = T(N-1) + N T(N-1) = T(N-2) + (N-1) T(N-2) = T(N-3) + (N-2) …

  • T(2) = T(1) + 2 T(N) = T(1) + 2 + 3 + 4 + … + N = N(N+1)/2 = O(N 2 ) Therefore, you never want to select a pivot element that leads to an unbalanced paritioning. Average Case: If each partition is equally likely to contain 0, 1, 2, …, N- elements, then the average running time of the quicksort algorithm is O(N log 2 N). More formally this is stated as: T(Left)average = T(Right)average = [T(0) + T(1) + T(2) + … + T(N-1)]/N T(N)average = T(Left)average + T(Right)average + N = 2[T(Left)average] + N = 2[[T(0) + T(1) + T(2) + … + T(N-1)]/N] + N with manipulation you arrive at: T(N)/(N+1) = T(N-1)/N + 2/(N+1) Telescoping yields: T(N)/(N+1) = 2[1 + ½ + 1/3 + …+1/(N+1)) – 5/ which is O(log 2 N). Therefore, multiplying both side by N+1 gives: T(N) = O(N log 2 N)

Picking the Pivot: Don’t do this randomly, or by picking the first element, or even by picking the larger of the first two elements. A safe way is to set low = first element and high = last element and calculating (low+high)/2. An even better way is to pick the median of three values low, middle and high. Lower Bound on Sorting We have seen that quicksort has a best case performance of O(N log N). The question becomes, can we do better? The bottom line is: any algorithm that sorts which uses only element (binary) comparisons will require (N log N) time in the worst case. This means that any algorithm that sorts by using element (binary) comparisons must use at least roughly N log N comparisons for some input sequence. This is also true for the average case performance. Consider the problem of sorting the sequence S = {a, b, c} composed of three distinct items; that is: a  b and a  c and b  c. The figure below illustrates a possible sorting algorithm in the form of a binary decision tree. Each node of the decision tree represents one binary comparison (in each node of the tree exactly two elements are compared). Since there are two possible outcomes for each comparison, each non-leaf node in the tree will be of degree two. Suppose that a < b < c in our example. Consider how the algorithm determines this fact. Y N Y N Y N Y N Y N A Decision Tree for Comparison Sorting a < b a < c a < c b < c b < c c < a < b b < a < c a < b < c a < c < b b < c < a c < b < a

If h is too small, then the subarray data(i) could be too large and the sort will remain inefficient. On the other hand, if h is too large, then too many small subarrays are created, and although they are sorted, the overall order of the original array will remain largely unchanged. If only one partition of the original array is performed – the gain in execution time will be slight. To solve this problem, several different subdivisions must be used, and for every subdivision, the same procedure will be applied separately. This is shown in the pseudocode algorithm shown below. This is the basic idea behind the Shell sort. The division of the array into several subarrays is done in such a fashion that elements spaced further apart are compared first, then the elements closer to each other are compared, and so on, until adjacent elements are compared on the last pass. The original array is subdivided into subarrays by picking every ht th element as part of one subarray. Therefore, there are ht subarrays, and for every h = 1, …, ht , For example, if ht = 3, the array data will be subdivided into three subarrays data 1 , data 2 , and data 3 so that: data 31 [0] = data[0], data 31 [1] = data[3], data 31 [2] = data[6], data 31 [i] = data[3i], … data 32 [0] = data[1], data 32 [1] = data[4], data 32 [2] = data[7], data 32 [i] = data[31+1], … data 33 [0] = data[2], data 33 [1] = data[5], data 33 [2] = data[8], data 33 [i] = data[3*1+2], … If ht = 3, the process of extracting subarrays and sorting them is called a 3-sort. If ht = 3, the process is called a 5-sort , and so on. divide data into h subarrays; for (i = 1; i ≤ h; i++) sort subarray data(i); sort array data; determine numbers ht... h 1 of ways of dividiny array data into subarrays; for (h = ht; t > 1; t--, h = ht) divide data into h subarrays for (i = 1; i ≤ h; i++) sort subarray data(i); sort array data; data (^) ht h[ i]data[hti(h 1 )]

Example – Shell Sort (same example – different view) Original 81 94 11 96 12 35 17 95 28 58 41 75 15 5 subarrays 35 81 41 before 17 94 75 sorting 11 95 28 96 12 58 5 subarrays 35 41 81 after 17 75 94 sorting 11 95 28 96 12 58 After 5-sort 35 17 11 28 12 41 75 15 96 58 81 94 95

Generic Java Implementation of Shell Sort void Shellsort (Object[ ] data) { int i, j, k, h, hCnt, increments[ ] = new int[20]; Comparable temp; // create an appropriate number of increments h for (h = 1, i = 0; h < data.length; i++) { increments[i] = h h = 3h + 1; } // loop on the number of different increments h for (i--; i ≥ 0; i--) { h = increments[i]; // loop on the number of subarrays h-sorted in the i th pass for (hCnt = h; hCnt < 2h; hCnt++) { //insertion sort for subarray containing every h th element of array data for (j = hCnt; j < data.length; ) { temp = (Comparable)data[j]; k = j; while (k-h ≥ 0 && temp.compareTo(data[k-h]) < 0) { data[k] = data[k-h]; k –= h; } data[k] = temp; j += h; } } } } Quicksort The quicksort algorithm was developed by C.A.R. Hoare and is a recursive divide and conquer approach to sorting. It is also the fastest known sort. The original array is divided into two subarrays, the first of which contains elements less than or equal to a chosen key called the bound or pivot. The second array includes elements equal to or greater than the pivot. The two subarrays can be sorted separately, but before this is done, the partition process is repeated for both subarrays. As a result, two new pivots are chosen, one for each subarray. The four subarrays are created because each subarray in the first phase is not divided into two segments. This process of partitioning the subarrays is continued until there are only one-cell arrays, which do not require sorting (by default an array of one element is sorted). Through the process of dividing task of sorting a large array

into two simpler tasks and then further dividing those tasks into even simpler tasks

  • it turns out that in the process of getting prepared to sort – the data have become sorted! Quicksort is an inherently recursive algorithm because it is applied to both subarrays of an array at each level of partitioning. A psuedocode version of quicksort is shown below. Pseudocode version quicksort (array[ ]) if array length > 1 chose pivot; // partition array into subarray1 and subarray while there are elements left in array if element < pivot include element in either subarray1 = {e1: e1  pivot}; or in subarray2 = {e1: e1  pivot}; quicksort(subarray1); quicksort(subarray2); To partition the array, two operations need to be performed: (1) a pivot has to be found and (2) the array must be scanned to place the elements into the proper subarrays. Choosing a good pivot is not a trivial task. The main problem is that the two subarrays should contain approximately the same number of elements. A number of different strategies exist for selecting a pivot. One of the simplest consists of choosing the first element of an array. For some situations this technique might suffice – however, since many arrays to be sorted already have many elements in the proper positions, a safer approach would be to chose the element in the middle of the array. Selecting the element which is the median of the elements in the array is the safest approach but is, in general, too costly and is simulated with median of three or median of five techniques. The task of scanning the array and dividing the elements between the two subarrays is rather vague in the pseudocode algorithm shown above and is in many ways implementation dependent. Notice in particular that the algorithm above does not specifically indicate to which subarray an element equal to the pivot belongs. This is done so that such elements can be used to balance the number of elements in the subarrays. Shown below is a Java implementation of a quicksort algorithm followed by an example of how the quicksort algorithm functions.

12]. Since the last element is already in its proper position – it requires no further processing. In the first partitioning lower =1 and upper =9 and the first element of the array8, is swapped with the pivot 6 in position 4, so the array becomes: [6, 5, 4, 7, 8, 1, 6, 3, 8, 10, 12] (see part (b) of the figure). In the first iteration of the outer while loop, the inner while loop moves lower to position 3 with 7, which is greater than the pivot. The second inner while loop moves upper to position 7 with 3, which is less than the pivot (see part (c)). Next the elements in these two cells are interchanged, producing the array [6, 5, 4, 3, 8, 1, 6, 7, 8, 10, 12] (see part (d)). Then lower is incremented to 4 and upper is decremented to 6 (see part (e)). This will conclude the first iteration of the outer while loop. In its second iteration, neither of the two inner while loops modifies any of the two indicies because lower indicates a position occupied by 8, which is greater than the pivot, and upper indicates a position occupied by 6, which is equal to the pivot. The two numbers are swapped (see part (f)) and both indicies are updated to 5 (see part (g)). In the third iteration of the outer while loop, lower is moved to the next position containing 8, which is greater than the pivot and upper stays at the same position because the 1 in this position is smaller than the piovt (see part (h)). But at that point, lower and upper cross each other, so no swapping occurs and after a redundant increment of lower to 7, the outer while loop terminates. At this point, upper is the index of the rightmost element of the first subarray (with the element not exceeding the pivot), so the element in this position is swapped with the pivot (see part (i)). In this fashion the pivot is placed in its final position and is excluded from subsequent processing. The two subarrays that are processed next are the left subarray, with elements to the left of the pivot and the right subarray with elements to the right of the pivot (see part (j)). Then the partitioning of these two subarrays begins separately, and then for the subarrays of these subarrays, until the subarrays have less than two elements. This entire process is summarized in the second of the two figures that follow. The worst case occurs if in each invocation of quicksort(), the smallest element of the array is chosen as the pivot. To see this try quicksort on the array [5, 3, 1, 2, 4, 6, 8]. The first pivot will be 1 causing an empty subarray and the subarray [3, 5, 2, 4, 6] to be formed. The new pivot is 2, which again will form an empty subarray plus the array [5, 3, 4, 6]. Thus, the algorithm operates on arrays of size n-1, n-2, …, 2. The partitions require n-2 + n-3+…+1 comparisons. This results in a run- time of O(N 2 ). The best case occurs when the pivot divides the array into two subarrays of equal size and will be O(N log N). Example - Paritioning the Array [8, 5, 4, 7, 6, 1, 6, 3, 8, 12, 10] with Quicksort( )

Example continued – Sorting the Array with Quicksort( )

Merge Sort The problem with the quicksort algorithm is that its complexity in the worst case is O(N^2 ) (although in reality this can be avoided) due to the difficulty in controlling the partitioning process. Different techniques for choosing the pivot will provide differing run-times unless the subarrays are of equal size. Another strategy is to make the partitioning process as simple as possible (unlike quicksort) and concentrate on the merging of the two sorted arrays. This is the strategy employed by the mergesort algorithm. Merge sort was one of the first sorting algorithms used on a computer and was developed by John von Neumann. The key process in mergesort is merging sorted halves of an array into one sorted array. However, these halves must first be sorted, which is accomplished by merging the already sorted halves of these halves, and so on. The process of dividing the arrays into two halves stops when the array has fewer than two elements. As with quicksort, mergesort is an inherently recursive algorithm and is summarized by the following pseudocode. Pseuodcode for Mergesort mergesort (data) if data have at least two elements mergesort( left half of data); mergesort( right half of data); merge( both halves into a sorted list ); Merging two subarrays into one is a relatively simple task as indicated by the following pseudocode algorithm: merge (array1, array2, array3) i1, i2, i3 are properly initialized while both array2 and array3 contain elements if array2[i2] < array3[i3] array1[i1++] = array2[i2++]; else array1[i1++] = array2[i3++]; load into array1 the remaining elements of either array2 or array3; Example Let array2 = [1, 4, 6, 8, 10] and array3 = [2, 3, 5, 22] then array1 = [1, 2, 3, 4, 5, 6, 8, 10, 22]. The pseudocode for merge( ) suggests that array1, array2, and array3 are physically separate entities. However, for the proper execution of mergesort( ),

array1 is a concatenation of array2 and array3 (see the pseudocode for mergesort()) so that, in the example above, array1 before the execution of merge( ) is [1, 4, 6, 8, 10, 2, 3, 5, 22]. In this situtation, merge( ) leads to erroneous results, since after the second iteration of the while loop, array2 is [1, 2, 6, 8, 10] and array1 is [1, 2, 6, 8, 10, 22, 3, 5, 22]. Therefore, a temporary array has to be used during the merging process. At the end of the merging process, the contents of this temporary array are transferred to array1. Because array2 and array3 are subarrays of array1, they do not need to be passed as parameters to merge( ). Instead, indices for the beginning and end of array1 are passed, since array1 can be part of another array. To reflect this the pseudocode for merge is modified to: merge (array1, first, last) mid = (first + last)/2; i1 = 0; i2 = first; i3 = mid+1; while both left and right subarrays of array1 contain elements if array1[i2] < array1[i3] temp[i1++] = array1[i2++]; else temp[i1++] = array1[i3++]; load into temp the remaining elements of array1; load into array1 the contents of temp; Since the entire array1 is copied to temp and then temp is copied back to array1, the number of movements in each execution of merge( ) is always the same and is equal to: 2  (last – first + 1). The number of comparisons depends on the ordering in array1. If array1 is in order or if the elements in the right half precede the elements in the left half, the number of comparisons is (first + last)/2. The worst case occurs when the last element of one half precedes only the last element of the other half, such as in [1, 6, 10, 12] and [5, 9, 11, 13]. In this case the number of comparisons is (last – first). For an n -element array, the number of comparisons is n-. mergesort (data, first, last) if (first < last) mid = (first + last)/2; mergesort (data, first, mid); mergesort (data, mid + 1, last); merge(data, first, last); The following diagram illustrates the mergesort algorithm.

mark1++; } else { temp[counter] = values[mark2]; mark2++; } counter++; } // Copy part of last array into temp array. if (mark1 <= mid) { for (int i=mark1; i<=mid; i++) { temp[counter] = values[i]; counter++; } } else { for (int i=mark2; i<=high; i++) { temp[counter] = values[i]; counter++; } } // Copy values back into original array. for (int i=low;i<=high;i++) values[i] = temp[i-low]; } public void MergeSort(int low, int high) { // Make recursive calls only if there is // more than one element in the array. if (high > low) { int mid = (low + high)/2; MergeSort(low, mid); MergeSort(mid+1,high); Merge(low,mid,high); } }

Analysis of Merge Sort If you look at the algorithm we do the following:

  1. Sort the first half of the array
  2. Sort the second half of the array
  3. Merge the two halves Let T(n) = the amount of time Merge Sort takes on a list of n values Then, step #1 takes T(n/2) time, as does step #2. Step #3 takes O(n) because we do one comparison for each number that gets sorted (in the subarray) correctly. Thus, we find can find a recurrence relation that T(n) satisfies: T(n) = 2T(n/2) + O(n). Using the Master Theorem, we find that T(n) = O(nlgn). In practice, Merge Sort is not usually used, due to the overhead of copying all the values in the Merge into a temporary array and then back again.