Skip to content

Instantly share code, notes, and snippets.

@bluedistro
Created April 12, 2019 08:21
Show Gist options
  • Save bluedistro/7fd8240c4def0cb99a13a92f0097e968 to your computer and use it in GitHub Desktop.
Save bluedistro/7fd8240c4def0cb99a13a92f0097e968 to your computer and use it in GitHub Desktop.
Insertion Sort and Merge Sort
def insertion_sort(array):
for i in range(1, len(array)):
data = array[i]
j = i
while j > 0 and array[j-1] > data:
array[j] = array[j - 1]
j -= 1
array[j] = data
return array
def mergesort(array):
if len(array) > 1:
# find the middleof the array
mid = len(array)//2
left = array[:mid]
right = array[mid:]
mergesort(left)
mergesort(right)
i=j=k=0
while i < len(left) and j < len(right):
if left[i] < right[j]:
array[k] = left[i]
i += 1
else:
array[k] = right[j]
j += 1
k += 1
while i < len(left):
array[k] = left[i]
i += 1
k += 1
while j < len(right):
array[k] = right[j]
j += 1
k += 1
return array
listed = [6, 11, 8, 3, 20, 9]
# print(insertion_sort(listed))
print(mergesort(listed))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment