Last active
June 1, 2019 04:12
-
-
Save Yossarian0916/6fd7c2abf6938e6b7150a6185aaf8d12 to your computer and use it in GitHub Desktop.
quick sort algorithm python implementation, and test case with randomly generated array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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