Note: This guide is not intended as a fully comprehensive guide to sorting, only a glimpse at how recursion can be used to effectively sort. For more information on the sorting algorithms described within (as well as other algorithms not mentioned), please see the SparkNote guide to sorting algorithms.
Recursive techniques can be utilized in sorting algorithms, allowing for the sorting of n elements in O(nlogn) time (compared with the O(n 2) efficiency of bubble sort. Two such algorithms which will be examined here are Mergesort and Quicksort.
To discuss mergesort, we must first discuss the merge operation, the process of combining to sorted data sets into one sorted data set. The merge operation can be accomplished in O(n) time.
Given two sorted data sets to merge, we start at the beginning of each:
We take the smallest element from the two we're comparing (these being the two elements at the front of the sets), and we move it into the new data set. This repetition is done until all of the elements have been moved, or until one of the lists is empty, at which point all of the elements in the non-empty list are moved to the new list, leaving them in the same order.
The following code implements the merge operation. It merges a1 and a2, and stores the merged list back into a1 (therefore a1 must be large enough to hold both lists):