import random
def partion(arr, l, r):
'''
Divid the array
The left part is less than the pivot
The right part is greater than the pivot
Then return the position of pivot
'''
i = l #i points to the END of left part
j = l + 1 #j points to the END of right part
x = arr[l] #pick the first one as pivot or pick it ramdomly
while j <= r: #quit the loop if j is out of the array
while j <= r and arr[j] >= x: #look for the element less than the pivot
j= j + 1
if j <= r: # it is found
arr[i+1], arr[j] = arr[j], arr[i+1] #swap with the one after i
j = j + 1 # we have one added to left, move to the next
i = i + 1 # move one to check the next element
arr[l], arr[i] = arr[i], arr[l] #divided by pivot
return i
def partion2(arr, l, r):
'''
This one seems easier to understand
'''
i = l
j = r
x = arr[l]
while i < j:
while i < j and arr[j] > x:#scan from right to left
j = j - 1
arr[i] = arr[j] #put it to the left
while i < j and arr[i] <= x: #scan from left to right
i = i + 1
arr[j] = arr[i] #put it to the right
arr[i] = x #at this time i must equal to j
return i
def quick_sort(arr, l, r):
if l < r: #condiction to quit, no need to sort
m = partion(arr, l, r)
quick_sort(arr, 0, m - 1) #sort the left part
quick_sort(arr, m + 1, r) #sort the right part
if __name__ == '__main__':
sample = [random.randrange(0, 100, 1) for i in range(10)]
original = sample[:]
print('Before: %s'%original)
quick_sort(sample, 0, len(sample)-1)
print('After: %s'%sample)
print('Corrected: %s'%(sample == sorted(original)))
Python - Quick Sort
最新推荐文章于 2024-05-14 10:51:55 发布