It is mainly divided into two subalgorithms. PARTITION (A, p, r) uses A [r] as the benchmark to divide the array. if it is smaller than A [r], it is placed on the left, QUICKSORT (A, p, r), which is larger than A [r], is A subroutine for fast sorting. The Division program is called to divide the array and then recursively call QUICKSORT (, p, r) to complete the fast 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)
The code is as follows:
X branch 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)
The code is as follows:
If p <r
Then q PARTITION (A, p, r)
QUICKSORT (A, p, q-1)
QUICKSORT (A, q + 1, r)
Implementation:
The 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" %)