Last active
April 20, 2020 03:22
-
-
Save amandaroos/3e552e5f2f7cab1088aaa1961b66e3d5 to your computer and use it in GitHub Desktop.
Quicksort 1
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
"""Implement quick sort in Python. | |
Input a list. | |
Output a sorted list.""" | |
def quicksort(array): | |
low = 0 | |
high = len(array)-1 | |
partition(array, low, high) | |
return array | |
def partition(array, testIndex, pivotIndex): | |
low = testIndex | |
high = pivotIndex | |
if testIndex == pivotIndex: | |
return None | |
while testIndex < pivotIndex: | |
if array[testIndex] > array[pivotIndex]: | |
if (pivotIndex - testIndex) != 1: | |
j = array[pivotIndex-1] | |
array[pivotIndex - 1] = array[pivotIndex] | |
array[pivotIndex] = array[testIndex] | |
array[testIndex] = j | |
else: | |
array[pivotIndex], array[testIndex] = array[testIndex], array[pivotIndex] | |
pivotIndex = pivotIndex - 1 | |
else: | |
testIndex = testIndex + 1 | |
partition(array, pivotIndex, high) | |
partition(array, low, pivotIndex-1) | |
test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14] | |
print quicksort(test) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment