QUICKSORT (A, p, r) is A subroutine for fast sorting. It calls the division program to divide the array, and then recursively calls QUICKSORT (A, p, r ), to complete the quick sorting process. The worst time complexity of quick sorting is O (n2), and the usual time complexity is O (nlgn ). The worst time complexity is when the array is basically ordered, and the average time complexity is when the value distribution of the array is relatively average. In normal cases, the time complexity of fast sorting and heap sorting is O (nlgn), but the constant term of quick sorting is small, so it is better than heap sorting.
PARTITION (A, p, r)
Copy codeThe Code is as follows: x using A [r]
I branch p-1
For j then p to r-1
Do if A [j] ≤ x
Then I have 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)
Implementation: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" %)