After reading about Strand Sort on Wikipedia and testing the provided Python version, I decided to try my hand at a faster implementation. I've studied the "Time Complexity" page, read many different approaches to mergesort (and borrowed some), tested the code myself with profiler, line_profiler
, and timeit
, and I think I've got sped up pretty well.
I'm looking for any ideas on how to optimize this code without changing the sorting algorithm itself or resorting to using Python's timsort
for any number of elements.
def strand_sort(array):
if len(array) < 2:
return array
result = []
while array:
i = 0
sublist = []
sublist.append(array.pop())
while i < len(array):
num = array[i]
if num > sublist[-1]:
sublist.append(num)
del array[i]
else:
i = i + 1
result = merge(list(result), sublist)
return result
def merge(list_1, list_2):
i = 0
j = 0
merged_list = []
while i < len(list_1) and j < len(list_2):
if list_1[i] > list_2[j]:
merged_list.append(list_2[j])
j += 1
else:
merged_list.append(list_1[i])
i += 1
merged_list += list_1[i:]
merged_list += list_2[j:]
return merged_list