Skip to content

Instantly share code, notes, and snippets.

@sap1ens
Forked from mailpraveens/mergesort
Last active March 31, 2017 04:40
Show Gist options
  • Save sap1ens/993062bf9020d859bff09347d8154172 to your computer and use it in GitHub Desktop.
Save sap1ens/993062bf9020d859bff09347d8154172 to your computer and use it in GitHub Desktop.
sort in python
#The merge method takes in the two subarrays and creates a output array
def merge(left, right):
result = []
i , j = 0 , 0
while i < len (left) and j < len (right): # iterate through both arrays and arrange the elements in sorted order
if left[i] <= right [j]:
result.append(left[i])
i+=1
else:
result.append(right[j])
j+=1
#The loop may break before all elements are copied hence append the remaining elements
result += left[i:]
result += right[j:]
return result
#The mergesort method to split the arrays into smaller subarrays
def mergesort(lst):
if len(lst) <= 1:
return lst
middle = int(len(lst) / 2)
left = mergesort(lst[:middle])
right = mergesort(lst[middle:])
return merge(left, right)
if __name__ == '__main__':
print mergesort([3, 4, 8, 0, 6, 7, 4, 2, 1, 9, 4, 5])
def sort(array=[12,4,5,6,7,3,1,15]):
less = []
equal = []
greater = []
if len(array) > 1:
pivot = array[0]
for x in array:
if x < pivot:
less.append(x)
if x == pivot:
equal.append(x)
if x > pivot:
greater.append(x)
# Don't forget to return something!
return sort(less)+equal+sort(greater) # Just use the + operator to join lists
# Note that you want equal ^^^^^ not pivot
else: # You need to hande the part at the end of the recursion - when you only have one element in your array, just return the array.
return array
def partition(array, begin, end):
pivot = begin
for i in xrange(begin+1, end+1):
if array[i] <= array[begin]:
pivot += 1
array[i], array[pivot] = array[pivot], array[i]
array[pivot], array[begin] = array[begin], array[pivot]
return pivot
def quicksort(array, begin=0, end=None):
if end is None:
end = len(array) - 1
def _quicksort(array, begin, end):
if begin >= end:
return
pivot = partition(array, begin, end)
_quicksort(array, begin, pivot-1)
_quicksort(array, pivot+1, end)
return _quicksort(array, begin, end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment