Array class or the Python
There are many algoriths but I believe some of the most known methods of sorting are:
Merge sort divides the list (array) of elements in sub-lists and then merges the sorted sub-lists to finally produce the complete sorted sequence. Wikipedia offers great pseudo-code and I implemented this on my example. It uses recursion for the division in sub-lists and because of the divide-and-conquer logic it can be also parallelized.
We start by writing the the main function that divides our list to two sub-lists and then proceeds with sorting each individual sub-list:
def merge_sort(a_list): length = len(a_list) if length <= 1: return a_list middle_index = length / 2 left = a_list[0:middle_index] right = a_list[middle_index:] left = merge_sort(left) right = merge_sort(right) return merge(left, right)
Let us take it step-by-step:
if length <= 1:
Return immediately if the list has only one element, which is a trivial case for sorting. Note that this is also the termination condition for the recursion!
middle_index = length / 2
left = a_list[0:middle_index]
right = a_list[middle_index:]
Find the middle of the list (
middle_index) and divide the input list into two distinct sub-lists,
left = merge_sort(left) right = merge_sort(right)
The recursive part: call
merge_sort for each of the new sub-lists,
right. Let’s say that we have an initial list of 10 elements that needs to be sorted; in the first call of
merge_sort the list will be divided into 2 sub-lists of 5 elements.
merge_sort will then be called for each of
right sub-lists. To be exact, the left sub-list must be completely sorted before proceeding to the right. Clearly these two sorting operations are independent and thus are good candidates for parallelisation.
Based on this simple logical deduction, we will later see how Python multiprocessing can be utilized to take advantage of this algorithmic property.As a final step in our algorithm, the two sub-lists must be merged to a single list, where all elements are now in sorting order.
Merging the distinct sub-lists
And the merge function which will merge 2 sorted subists:
def merge(left, right): sorted_list =  # We create shallow copies so that we do not mutate # the original objects. left = left[:] right = right[:] # We do not have to actually inspect the length, # as empty lists truth value evaluates to False. # This is for algorithm demonstration purposes. while len(left) > 0 or len(right) > 0: if len(left) > 0 and len(right) > 0: if left 0: sorted_list.append(left.pop(0)) elif len(right) > 0: sorted_list.append(right.pop(0)) return sorted_list
Taking it a bit step-by-step again:
while len(left) > 0 or len(right) > 0:
We need to exhaust both lists. Remember that the element count may be different by one element if the total length of the initial list is odd.
if len(left) > 0 and len(right) > 0:
If both lists are not exhausted, then:
if left 0: sorted_list.append(left.pop(0)) elif len(right) > 0: sorted_list.append(right.pop(0))
If either one of the two lists is exhausted then continue extracting elements from the non-empty list.
In second thought, this could probably be done in a single step, which will save some computational time:
elif len(left) > 0: sorted_list.extend(left) break elif len(right) > 0: sorted_list.extend(right) break
Finally, the function returns the merged list which now contains all initial elements in ascending order.
For small lists this procedure is rather trivial for the core of a modern CPU. But what happens when a list has a significant size? We talked about parallelization. Without having to modify the code of the functions described previously, we could just divide our list in a number of sub-lists equal to the number of cores at our disposal and assign each to a different process.
Caveat: the final merging will be accomplished by a single core, which is the largest fraction of the algorithm’s time. Nevertheless, the process speeds up significantly for large lists. An additional note, the process of spawning new processes (
fork system calls) will notably delay the overall procedure for small lists. Apparently, the amount of time required for creating the objects and handling the multiple processes (let’s call this
MP) becomes a less significant factor for large lists, as the percentage of MP over the total sorting time (let’s call this
S), diminishes with the increase in the denominator.
Putting it all together
I have written an annotated version of the parallel MergeSort version using Python multiprocessing:
I have executed some test runs on a VPS, which uses a 4-core CPU, Intel Xeon L5520 @ 2.27GHz. However, available CPU time fluctuates due to other VMs consuming resources from time to time. All time measurements are in seconds. The two charts display the change in processing time (y-axis) as a function of the number of list elements (x-axis).
- Single Process Time
- Multiple Process Time
- Multi-process Final Merge Time
Using 2 cores
|Elements||SP||MP||MP/SP (%)||MPMT||MPMT/MP (%)|
Using 4 cores
|Elements||SP||MP||MP/SP (%)||MPMT||MPMT/MP (%)|
I would be more than happy to read any comments or answer any questions!