Python Quick Sort
Quick sort uses a divide-and-conquer strategy to split a sequence (list) into two smaller subsequences, then recursively sorts both subsequences.
The steps are:
- Pick a pivot: choose an element from the sequence and call it the "pivot";
- Partition: reorder the sequence so that all elements smaller than the pivot are placed before it and all elements larger than the pivot after it (elements equal to the pivot can go on either side). After this partition, the pivot is in its final sorted position;
- Recursively sort the subsequences: recursively sort the subsequence of elements smaller than the pivot and the subsequence of elements larger than the pivot.
The recursion reaches its base case when the size of the sequence is zero or one, at which point it is obviously already sorted.
There are several concrete ways to choose the pivot, and this choice has a decisive effect on the sorting performance.
Example
def
partition
(
arr
,
low
,
high
)
:
i
=
(
low
1
)
Index of the smallest element
pivot
=
arr
[
high
]
for
j
in
range
(
low
,
high
)
:
The current element is less than or equal to the pivot
if
arr
[
j
]
<=
pivot
:
i
=
i
1
arr
[
i
]
,
arr
[
j
]
=
arr
[
j
]
,
arr
[
i
]
arr
[
i
1
]
,
arr
[
high
]
=
arr
[
high
]
,
arr
[
i
1
]
return
(
i
1
)
arr[] --> array to sort
low --> starting index
high --> ending index
Quick sort function
def
quickSort
(
arr
,
low
,
high
)
:
if
low
<
high
:
pi
=
partition
(
arr
,
low
,
high
)
quickSort
(
arr
,
low
,
pi
1
)
quickSort
(
arr
,
pi
1
,
high
)
arr
=
[
10
,
7
,
8
,
9
,
1
,
5
]
n
=
len
(
arr
)
quickSort
(
arr
,
0
,
n
1
)
(
"
Sorted array:
"
)
for
i
in
range
(
n
)
:
(
"
%d
"
%
arr
[
i
]
)
,
The output of the code above is:
Sorted array:
1
5
7
8
9
10
Python3 Examples