Python algorithm sort to achieve quick sort

  • 2020-04-02 09:40:53
  • OfStack

QUICKSORT(A, p, r) is A QUICKSORT subroutine that calls the divider to divide an array and then recursively calls QUICKSORT(A, p, r) to perform the QUICKSORT process. The worst time complexity of quicksort is O(n2) and the normal time complexity is O(NLGN). The worst time complexity is when the array is basically in order, and the average time complexity is when the array is evenly distributed. Under normal circumstances, the time complexity of quicksort and heap sort is O(NLGN), but the constant term of quicksort is small, so it is better than heap sort.
PARTITION (A, p, r)
 
x  please  A[r] 
i  please  p - 1 
for j  please  p to r - 1 
do if A[j]  Or less  x 
then i  please  i + 1 
swap(A[i], A[j]) 
swap(A[i + 1], A[r]) 
return i + 1 

QUICKSORT (A, p, r)
 
if p < r 
then q  please  PARTITION(A, p, r) 
QUICKSORT(A, p, q - 1) 
QUICKSORT(A, q + 1, r) 

Implementation:
 
#!/usr/bin/python 
import sys 
def partion(array, p, r): 
x = array[r] 
i = p - 1 
for j in range(p, r): 
if (array[j] < x): 
i+=1 
array[j], array[i] = array[i], array[j] 
i+=1 
array[i], array[r] = array[r], array[i] 
return i 
def quick_sort(array, p, r): 
if p < r: 
q = partion(array, p, r) 
quick_sort(array, p, q - 1) 
quick_sort(array, q + 1, r) 
if __name__ == "__main__": 
array = [1, 3, 5, 23, 64, 7, 23, 6, 34, 98, 100, 9] 
quick_sort(array, 0, len(array) - 1) 
for a in array: 
sys.stdout.write("%d " % a) 

Related articles: