Quick Sort
Quick sort is based on divide and conquer paradigm. Here is the three step divide and conquer process for
sorting a typical subarray
Divide: The array
A [q+1. . r ]
A [ p.. r ] .
A [ p.. r ]
is partitioned(rearranged) into two nonempty subarrays
such that each element of
A [ p.. q ]
A [ p.. q ] and
is smaller or equal to each element of
A [q+1. . r ] . The index q is computed as part of this partitioning procedure.
Conquer: The two subarrays
A [ p.. q ] and
A [q+1. . r ] are sorted by recursive calls to quicksort.
Combine: Since the subarrays are sorted in place, no work is needed to combine them. The entire array is
now sorted.
The following procedure implements quicksort
Quicksort ( A , p ,r )
If ( p<r )
q partition( A , p , r )
Quicksort ( A , p ,q)
Quicksort ( A , q+1, r )
To sort an entire array A, the initial call is Quicksort( A , 1,lengt h[ A]
Partitioning the array: The key to the algorithm is partition procedure which rearranges the subarray
A [ p.. r ] in place.
Partition( A , p , r )
x A[p]
i p1
J r =1
w h ile (TRUE)
do
repeat
j j1
until ( A [ j ] x)
repeat
i i+1
until ( A [ i ] x )
If (i< j)
T h en exc h ange ( A [ i], A [ j])
else return j
Explanation of the Partition algorithm:
It selects an element
regions
A [ p .. i ]
x= A[ p]
and
A [ j ..r ]
A [ p.. r ]
from the array
as a pivot element. It then grows two
from the top and bottom of A[p..r], respectively such that every
element in A[p..i] is less than or equal to
x . Initially i= p1 and
j=r +1 , so these regions are
empty.
Within the body of the while loop, the index
A [ i ] x A [ j ] . Thus
A [i]
is decremented and index i is incremented until
is too large to belong to the bottom region and A[j] is too small to
A [i]
belong to the top region. Thus by interchanging
and
A [ j ] , we can extend the two
subregions.
Conceptually , the partitioning procedure performs a simple function. It puts elements smaller than
into the bottom of the array and elements larger than
x into the top region.
A [ p.. r ] is O(n) where n=r p+1.
Running time of partition on an array
Example of partiotion algorithm:
Consider the following array
5
Pivot=A[0]=5