Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Quick Sort

Python Quick Sort

Document Object Reference Manual Python3 Examples

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:

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

)

print

(

"

Sorted array:

"

)

for

i

in

range

(

n

)

:

print

(

"

%d

"

%

arr

[

i

]

)

,

The output of the code above is:


Sorted array:
1
5
7
8
9
10

Document Object Reference Manual Python3 Examples