Searching and Sorting 579
Thus, the number of comparisons is proportional to (n2). The time complexity of bubble sort is
0 (n2).
16.9 QUICKSORT
It is also known as partition exchange sort. It was invented by C A R Hoare. It is based on partition.
Hence, the method falls under divide and conquer technique. The main list of element is divided
into two sub-lists. For example, suppose a list of X elements are to be sorted. The quick sort marks
an element in a list called as pivot or key. Consider the first element / as a pivot. Shift all the
elements whose value is less than J towards the left and elements whose value is grater than J to
right of J. Now, the key element divides the main list in to two parts. It is not necessary that
selected key element must be at middle. Any element from the list can act as key element. However,
for best performance preference is given to middle elements. Time consumption of the quick sort
depends on the location of the key in the list.
Consider the following example in which five elements 8, 9, 7, 6, 4 are to be sorted using quick
sort. Fig. 16.6 illustrates it.
Consider Pass 1 under which the following iterations are made. Similar operations are done in
Pass 2, Pass 3, etc.
In Iteration 1 the first element 8 is marked as pivot one. It is compared with the last element
whose value is 4. Here 4 is smaller than 8 hence the numbers are swapped. Iteration 2 shows the
swapping operation.
In the Iteration 3 and 4, the position of 8 is fixed. In Iteration 2, 8 and 9 are compared and
swapping is done after Iteration 2.
In Iteration 3,8 and 6 are compared and necessary swapping is done. After this, it is impossible
to swap. Hence, the position of 8 is fixed. Because of fixing the position of 8 the main list is divided
into two parts. Towards left of 8 elements having smaller than 8 are placed and towards the right
greater than 8 are placed.
Towards the right of 8 only one element is present hence there is no need of further swapping.
This may be considered under Pass 2.
However towards the left of 8 there are three elements and these elements are to be swapped as
per the procedure described above. This may be considered under Pass 3.
Pass 1
Fig. 16.6 Quick sort
Iteration 2
Iteration 3
Iteration 4
Iteration 1