Skip to content

Instantly share code, notes, and snippets.

@re4lfl0w
Created October 17, 2015 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save re4lfl0w/091d11f4a666303937ea to your computer and use it in GitHub Desktop.
Save re4lfl0w/091d11f4a666303937ea to your computer and use it in GitHub Desktop.
Quick Sort with python
# How efficient to get pivot?
def get_pivot(array, left, right):
# 현재 잘 안되고 있음
if abs(left-right) > 2:
mid = len(array) // 2
first = 0
last = len(array) - 1
dic = {first: array[first],
mid: array[mid],
last: array[right]}
min_ = array[first]
max_ = array[last]
for k, v in dic.items():
if v < min_:
min_ = k
if v > max_:
max_ = k
pivot = [k for k, v in dic.items() if not dic[k] or not dic[k]][0]
# print('')
else:
pivot = left
pivot = left
return pivot
def partition(array, left, right):
pivot = get_pivot(array, left, right)
while True:
while array[left] <= array[pivot]:
left += 1
while array[right] > array[pivot]:
right -= 1
if left < right:
array[left], array[right] = array[right], array[left]
else:
break
array[pivot], array[right] = array[right], array[pivot]
return right
def quicksort(array, begin=0, end=None):
if end is None:
end = len(array) - 1
if begin >= end:
return
pivot = partition(array, begin, end)
quicksort(array, begin, pivot-1)
quicksort(array, pivot+1, end)
array = [54,26,93,17,77,31,31,44,55,20]
print(array)
quicksort(array)
print(array)
# [17, 20, 26, 31, 31, 44, 54, 55, 77, 93]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment