Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Quick Sort

• Select a pivot (partitioning element) – here, the first element


• Rearrange the list so that all the elements in the first s
positions are smaller than or equal to the pivot and all the
elements in the remaining n-s positions are larger than or
equal to the pivot (see next slide for an algorithm)

A[i]≤p A[i]≥p

• Exchange the pivot with the last element in the first (i.e., ≤)
subarray — the pivot is now in its final position
• Sort the two subarrays recursively.
Quick Sort
• Algorithm Quick(A[0……n-1],low,high)
• Pblm: sorting of array A[0…n-1]
• i/p: An array A[0….n-1]in which unsorted elmts are
given.low indicates leftmost elmt in the list and high
indicates the rightmost elmt in the list.
• o/p: sorted in ascending order.
• If(low<high)then
• //split the array into two sub arrays
• m partition(A[low…high])//m is mid of the array.
• Quick(A[low…m-1])
• Quick(A[mid+1….high])
Quick Sort
• Algorithm partition(A[low…high])
• Pblm: partition the subarray using the first element as
pivot element.
• i/p:subarray A with low as lower most index of the
array and high as higher most index of the array.
• o/p: partitioning of array A is done and pivot
occupies its proper position. And the rightmost index
of the list is returned.
pivot A[low]
i low
j high+1
While(i<=j)do
{
While(A[i]<=pivot) do
i i+1
While(A[j]>=pivot) do
j j-1
If(i<=j)then
Swap(A[i],A[j]) / /swap A[i] and A[j]
}
Swap(A[low],A[j] ) //when i crosses j swap A[low] and
A[j]
Return j //rightmost index of the list
• o/p array is 1 2 3 4 5 7 8 9
Analysis
Best Case-split in the middle
Recurrence relation
C(n)=C(n/2)+C(n/2) + n for n>1
C(n/2) time required to sort left and right subarray.
n time required for partitioning the subarray.
With initial condition: C(1)=0
• In the worst case, one of the two subarrays will be
empty arrays, i.e., for inputs for which the
problem is already solved
• if A[0..n − 1] is a strictly increasing array and we
use A[0] as the pivot, the left-to-right scan will
stop on A[1] while the right-to-left scan will go all
the way to reach A[0], indicating the split at
position 0.
• So, after making n + 1 comparisons to get to this
partition and exchanging the pivot A[0] with itself,
the algorithm will be left with the strictly
increasing array A[1..n − 1] to sort.
• The total number of key comparisons made
will be equal to
• Cworst(n)=(n+1)+n+(n-1)+(n-2)+….2+1
• Let Cavg(n) be the average number of key
comparisons made by quicksort on a randomly
ordered array of size n.
• A partition can happen in any position s (0 ≤ s ≤
n−1) after n+1comparisons are made to achieve
the partition.
• After the partition, the left and right subarrays
will have s and n − 1− s elements, respectively.
• Assuming that the partition split can happen in
each position s with the same probability 1/n,
we get the following recurrence relation:
• we get the following recurrence relation:
m

You might also like