Skip to content

Instantly share code, notes, and snippets.

@smallyunet
Last active March 25, 2020 12:08
Show Gist options
  • Save smallyunet/308e7e69ab8c30e1c9bc9c420cc14674 to your computer and use it in GitHub Desktop.
Save smallyunet/308e7e69ab8c30e1c9bc9c420cc14674 to your computer and use it in GitHub Desktop.
quick sort by python
"""
@desc quick sort python version
@param List arr
@return List arr
"""
def quickSort(arr, left=None, right=None):
# default parameter
if left == None or right == None:
left = 0
right = len(arr) - 1
# handler
m = arr[left]
i = left+1
j = right
# loop until i==j
while i < j:
# j before i
while arr[j] >= m and i < j:
j -= 1
while arr[i] < m and i < j:
i += 1
if i != j:
arr[i] = arr[i] + arr[j]
arr[j] = arr[i] - arr[j]
arr[i] = arr[i] - arr[j]
# if j find number less than m
if m > arr[j]:
arr[left] = arr[left] + arr[j]
arr[j] = arr[left] - arr[j]
arr[left] = arr[left] - arr[j]
# control boundary
if left < i-1:
quickSort(arr, left, i-1)
if i+1 < right:
quickSort(arr, i+1, right)
return arr
# a = quickSort([6,1,2,7,9,3,4,5,10,8])
# print(a)
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment