L4-5: increases the size of the temp array if necessary.
L5: unchecked type Object to T[].
What is the advantage of declaring the member field temp?
The helper method can be defined as follows:
/** * @param input the input array. * @param temp the array to hold the copy of the input array. * @param beginIndex the beginning index of the 1st half (inclusive). * @param endIndex the ending index of the 2nd half (exclusive). */protectedvoidsort(T[] input,T[] copy,int beginIndex,int endIndex) {if (beginIndex +1>= endIndex) return;int middleIndex =Utils.getMiddleIndex(beginIndex, endIndex);sort(input, copy, beginIndex, middleIndex);sort(input, copy, middleIndex, endIndex);merge(input, copy, beginIndex, middleIndex, endIndex);}
L11: sorts the left sub-array.
L12: sorts the right sub-array.
L13: merges the left and right sub-arrays.
Finally, the merge() method can be defined as follows:
/** * @param input the input array. * @param temp the array to hold the copy of the input array. * @param beginIndex the beginning index of the 1st half (inclusive). * @param middleIndex the ending index of the 1st half (exclusive). * @param endIndex the ending index of the 2nd half (exclusive). */protectedvoidmerge(T[] input,T[] copy,int beginIndex,int middleIndex,int endIndex) {int fst = beginIndex, snd = middleIndex, n = endIndex - beginIndex;System.arraycopy(input, beginIndex, copy, beginIndex, n); assignments += n;for (int k = beginIndex; k < endIndex; k++) {if (fst >= middleIndex)assign(input, k, copy[snd++]);elseif (snd >= endIndex)assign(input, k, copy[fst++]);elseif (compareTo(copy, fst, snd)<0)assign(input, k, copy[fst++]);elseassign(input, k, copy[snd++]); }}
L10-11: copies the input array to the temporary array and counts the assignments.
L14-15: no key left in the 1st half.
L16-17: no key left in the 2nd half.
L18-19: the 2nd key is greater than the 1st key.
L20-21: the 1st key is greater than or equal to the 2nd key.
Quick Sort
Pick a pivot key in the input array.
Exchange keys between the left and right partitions such that all keys in the left and right partitions are smaller or bigger than the pivot key, respectively.
Repeat this procedure in each partition, recursively.
Let us create the QuickSort class inheriting AbstractSort:
L4-5: switches to the other sorting algorithm if the depth of the partitioning exceeds the max depth.
Benchmarks
The following shows runtime speeds, assignment costs, and comparison costs between several sorting algorithms for the random, best, and worst cases.
How many assignments are made for the n number of keys by the above version of MergeSort?
Although Quick Sort is the fastest on average, the worst-case complexity is O(n2).
∃ sorting algorithms that guarantee faster worst-case complexities than Quick Sort:
⇒ Quick Sort for random cases and a different algorithm for the worst case.