Skip to content

Instantly share code, notes, and snippets.

@kdaily
Last active March 26, 2020 18:54
Show Gist options
  • Save kdaily/d18c5650aa8849afd7198b8ab22c322d to your computer and use it in GitHub Desktop.
Save kdaily/d18c5650aa8849afd7198b8ab22c322d to your computer and use it in GitHub Desktop.
class Counter(object):
value = 0
def mergeSort(myList):
if len(myList) > 1:
depth.value += 1
mid = (len(myList) + 1) // 2
left = myList[:mid]
right = myList[mid:]
print(f"left = {left}, right = {right}")
# Recursive call on each half
mergeSort(left)
mergeSort(right)
# Two iterators for traversing the two halves
i = 0
j = 0
# Iterator for the main list
k = 0
while i < len(left) and j < len(right):
merge.value += 1
print(f"comparing position {i} ({left[i]}) from left and {j} ({right[j]}) from right")
if left[i] < right[j]:
# The value from the left half has been used
print(f"putting left {left[i]} at position {k}")
myList[k] = left[i]
# Move the iterator forward
i += 1
else:
# The value from the left half has been used
print(f"putting right {right[j]} at position {k}")
myList[k] = right[j]
j += 1
# Move to the next slot
k += 1
print(f"now, i, j, k = {i}, {j}, {k}")
# For all the remaining values
while i < len(left):
print(f"adding remaining left {left[i]} to position {k}")
myList[k] = left[i]
i += 1
k += 1
while j < len(right):
print(f"adding remaining left {right[j]} to position {k}")
myList[k]=right[j]
j += 1
k += 1
else:
print("list len is <= 1")
depth = Counter()
merge = Counter()
myList = [83,20,9,50,115,61,17]
mergeSort(myList)
print(myList)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment