Skip to content

Instantly share code, notes, and snippets.

@erictt erictt/sort.py
Last active Oct 19, 2018

Embed
What would you like to do?
Quick Sort & Merge Sort with Python 3
def quicksort(items):
if len(items) <= 1:
return items
pivot = items.pop()
leftItems = []
rightItems = []
for i in items:
if i <= pivot:
leftItems.append(i)
else:
rightItems.append(i)
return quicksort(leftItems) + [pivot] + quicksort(rightItems)
def mergesort(items):
lenItems = len(items)
if lenItems == 1:
return items
left = mergesort(items[:lenItems//2])
right = mergesort(items[lenItems//2:])
if left[len(left)-1] <= right[0]:
return left + right
elif right[len(right)-1] <= left[0]:
return right + left
i,j = 0,0
merged = []
while i < len(left) and j < len(right):
if left[i] < right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
merged += left[i:]
merged += right[j:]
return merged
items = [2, 4, 5, 1, 9, 5, 23 ,7, 12]
print(mergesort(items))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.