I was working on an assignment and I was hoping to know if the merge sort algorithm I wrote in Python was not making any unnecessary computations.
def sort(some_list):
if len(some_list) > 1:
return merge(sort(some_list.__getslice__(0, len(some_list)/2)),\
sort(some_list.__getslice__(len(some_list)/2, len(some_list))))
else:
return some_list
def merge(list_left, list_right):
sorted_list = []
while len(list_left) > 0 or len(list_right) > 0:
if len(list_left) == 0:
sorted_list.append(list_right.pop(0))
elif len(list_right) == 0:
sorted_list.append(list_left.pop(0))
elif list_left[0] < list_right[0]:
sorted_list.append(list_left.pop(0))
else:
sorted_list.append(list_right.pop(0))
return sorted_list
I did some testing by calling time function to check how much time it took to merge a list of numbers of size 100,000 with different presortedness values (where a presortedness = 0 means it's completely random and presortedness = 1 means the list is already sorted).
I'm using a core i7 processor and working from PyCharm on an Ubuntu 14.04 OS.
This was my result:
-------Test for Merge Sort---------------- Presortedness = 0.00 (completely random) Time elapsed = 1.90153600 Presortedness = 0.25 Time elapsed = 1.89535800 Presortedness = 0.50 Time elapsed = 1.90894200 Presortedness = 0.75 Time elapsed = 1.90660100 Presortedness = 1.00 (sorted) Time elapsed = 1.79297100