A (P.. R) A (P.. R) A (P.. Q) A (q+1. - R) A (P.. Q) A (q+1. - R) A (P.. Q) A (q+1. - R)
A (P.. R) A (P.. R) A (P.. Q) A (q+1. - R) A (P.. Q) A (q+1. - R) A (P.. Q) A (q+1. - R)
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 ]
A [ p.. q ]
A [ p.. q ] and
A [ p.. q ] and
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)
A [ p .. i ]
x= A[ p]
and
A [ j ..r ]
A [ p.. r ]
from the top and bottom of A[p..r], respectively such that every
x . Initially i= p1 and
empty.
Within the body of the while loop, the index
A [ i ] x A [ j ] . Thus
A [i]
is too large to belong to the bottom region and A[j] is too small to
A [i]
and
subregions.
Conceptually , the partitioning procedure performs a simple function. It puts elements smaller than
into the bottom of the array and elements larger than
Pivot=A[0]=5