Created
July 29, 2018 16:56
-
-
Save ianwcarlson/b7d2b2f834a845a47e6140483ffb5b95 to your computer and use it in GitHub Desktop.
Quick sort implementation in Python
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
"""Implement quick sort in Python. | |
Input a list. | |
Output a sorted list.""" | |
def sort_slice(list_slice): | |
# pivot location always starts on the right | |
end_idx = len(list_slice) - 1 | |
pivot_idx = end_idx | |
# compare location always starts on the left | |
compare_idx = 0 | |
while(True): | |
pivot_value = list_slice[pivot_idx] | |
compare_value = list_slice[compare_idx] | |
# If the pivot location starts out the same of the compare location then | |
# sorting is completely done for this slice and can be returned | |
if (pivot_idx == 0): | |
return list_slice | |
# If pivot is less than comparison, shift the pivot to the left | |
if (pivot_value < compare_value): | |
list_slice[compare_idx] = list_slice[pivot_idx - 1] | |
list_slice[pivot_idx - 1] = list_slice[pivot_idx] | |
list_slice[pivot_idx] = compare_value | |
pivot_idx -= 1 | |
# If pivot is greater than the comparison, shift the comparison to the right | |
elif (pivot_value > compare_value): | |
compare_idx += 1 | |
# Pivot is determined, now we need to recursively sort left and right sides | |
else: | |
left_slice = sort_slice(list_slice[0:pivot_idx]) | |
right_slice = [] | |
if (pivot_idx < end_idx): | |
right_slice = sort_slice(list_slice[pivot_idx+1:]) | |
# Finally, return the concatenated parts of the sorted list | |
return left_slice + [pivot_value] + right_slice | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment