QUICKSORT (A, p, R) is a subroutine that quickly sorts, calls the partitioning program to divide the array, and then recursively calls QUICKSORT (A, p, R) to complete the process of fast sorting. The worst time complexity for fast sorting is O (N2), and the time complexity is O (NLGN). The worst-case-time complexity is when the average time complexity of an array is more than the average when the number of times is fairly uniform. In peacetime, the time complexity of fast sorting and heap sorting is O (NLGN), but the fast sort constant is smaller, so it is better than heap sorting.
PARTITION (A, p, R)
Copy CodeThe code is as follows:
X←A[R]
I←p-1
For J←p to R-1
Do if a[j]≤x
Then i←i + 1
Swap (A[i], a[j])
Swap (A[i + 1], A[r])
return i + 1
QUICKSORT (A, p, R)
Copy CodeThe code is as follows:
If P < r
Then Q←partition (A, p, R)
QUICKSORT (A, p, q-1)
QUICKSORT (A, q + 1, R)
Realize:
Copy CodeThe code is as follows:
#!/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)