Created
October 17, 2018 06:30
-
-
Save scientificRat/c7a8c1f3ae5cec8ed1c1a129f143770b to your computer and use it in GitHub Desktop.
python quicksort
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
def quick_sort(array): | |
def partition(array, start, end): | |
i = start - 1 # i represent the last index of smaller set | |
pivot = end - 1 | |
# j represent the working pointer | |
for j in range(start, end - 1): | |
# swap | |
if array[j] < array[pivot]: | |
i += 1 | |
tmp = array[j] | |
array[j] = array[i] | |
array[i] = tmp | |
tmp = array[pivot] | |
array[pivot] = array[i + 1] | |
array[i + 1] = tmp | |
return i + 1 | |
def _quick_sort(array, start, end): | |
if end - start <= 1: | |
return | |
if end - start == 2: | |
if array[start] > array[end - 1]: | |
tmp = array[start] | |
array[start] = array[end - 1] | |
array[end - 1] = tmp | |
return | |
divide = partition(array, start, end) | |
if divide == end or divide == start: | |
return | |
_quick_sort(array, start, divide) | |
_quick_sort(array, divide, end) | |
return | |
_quick_sort(array, 0, len(array)) | |
return array |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment