This my implementation of the Merge Sorting Algorithm:
def merge(series1, series2):
output = []
while series1 != [] or series2 != []:
if series1 == []:
output.append(series2[0])
series2.pop(0)
continue
if series2 == []:
output.append(series1[0])
series1.pop(0)
continue
last1 = series1[0]
last2 = series2[0]
if last1 <= last2:
series1.pop(0)
output.append(last1)
continue
if last2 < last1:
series2.pop(0)
output.append(last2)
continue
return output
def is_even(x):
if x%2 == 0:
return True
return False
def merge_sort(series):
iseries = []
for i in series:
iseries.append([i])
while len(iseries) > 1:
output = []
length = len(iseries)
if not is_even(length):
length -= 1
for i in range(0, (length-1), 2):
a = iseries[i]
b = iseries[i+1]
output.append(merge(a, b))
output.append(iseries[-1])
else:
for i in range(0, (length-1), 2):
a = iseries[i]
b = iseries[i+1]
output.append(merge(a, b))
iseries = []
iseries += output
return iseries[0]
Basically it splits the items in the initial series into lists of one item (series
to iseries
). Then I merge the items two-by-two appending the new items to another list (output
), and set the main series equals to output
. I do this until it's 1 item only and return the 1st item (return iseries[0]
).