Example. Merge Sort
[comp1110-29]
Example. Merge Sort
[comp1110-29]Merge sort is both an efficient sorting algorithm (although it is not in-place) and a classic example
of Divide and Conquer techniques. The algorithm works by dividing the input array in half, recursively sorting each half, and then merging the results. We can write an efficient merge function that combines two sorted lists into a single combined sorted lists. Note that we just loop through both arrays once, so this merge function is more efficient than simply appending the two arrays and then sorting them by other means.
This function consistutes the "combine" step in the divide and conquer strategy. Now all that is left is the "dividing" and "conquering":
Note: This functions efficiency can be slightly improved by only allocating one output array and passing it into each function, however this obscures the functionality of the algorithm.