Last active
April 3, 2021 14:07
-
-
Save kaenova/99f5b19339172a839a91047a0a9dc98d to your computer and use it in GitHub Desktop.
A Quicksort Algorithm in Python
This file contains hidden or 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
def quicksort(lst, sort='asc'): | |
#Use 'asc' for ascending sort | |
#Use 'dsc' for descending sort | |
if (len(lst) == 1): | |
return lst | |
elif (len(lst) == 2): | |
if sort == 'asc': | |
if lst[0] >lst[1]: | |
lst[0], lst[1] = lst[1], lst[0] | |
return lst | |
if sort == 'dsc': | |
if lst[0] >lst[1]: | |
lst[0], lst[1] = lst[1], lst[0] | |
return lst | |
else: | |
pivot = lst[len(lst) - 1] | |
i = 0 | |
if sort == 'asc': | |
for j in range(len(lst) - 1): | |
if lst[j] <= pivot: | |
lst[i], lst[j] = lst[j], lst[i] | |
i+= 1 | |
if sort == 'dsc': | |
for j in range(len(lst) - 1): | |
if lst[j] >= pivot: | |
lst[i], lst[j] = lst[j], lst[i] | |
i+= 1 | |
if i == 0: | |
gabungan = [pivot] + quicksort(lst[:len(lst) - 1]) | |
elif pivot < lst[i]: | |
lst[i], lst[len(lst) - 1] = pivot, lst[i] | |
lst_kiri = quicksort(lst[:i], sort) | |
lst_kanan = quicksort(lst[(i+1):], sort) | |
gabungan = lst_kiri + [lst[i]] + lst_kanan | |
else: | |
gabungan = quicksort(lst[:len(lst) - 1], sort) + [pivot] | |
return gabungan |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment