Skip to content

Instantly share code, notes, and snippets.

@Yossarian0916
Last active June 1, 2019 04:12
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 Yossarian0916/6fd7c2abf6938e6b7150a6185aaf8d12 to your computer and use it in GitHub Desktop.
Save Yossarian0916/6fd7c2abf6938e6b7150a6185aaf8d12 to your computer and use it in GitHub Desktop.
quick sort algorithm python implementation, and test case with randomly generated array
import random
def partition(array, l, r):
pivot = array[l] # choose the 1st element as the pivot
i = l+1
for j in range(l+1, r):
if array[j] < pivot:
array[j], array[i] = array[i], array[j]
i += 1
array[l], array[i-1] = array[i-1], array[l]
return i-1
def random_partition(array, l, r):
i = random.randrange(l, r)
array[l], array[i] = array[i], array[l]
return partition(array, l, r)
def quick_sort(array, l, r):
if l < r:
p = partition(array, l, r)
quick_sort(array, l, p)
quick_sort(array, p+1, r)
if __name__ == "__main__":
lst = random.choices(range(1000), k=20)
# output
print('input: ', lst)
quick_sort(lst, 0, len(lst))
print('sorted:', lst)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment