Lec 6
Lec 6
Lecture 6: August 14
Instructor: Prof. Prateek Vishnoi Indian Institute of Technology, Mandi
In the previous class, we have seen a sorting algorithm(Merge Sort) that has time complexity Θ(n log n) and
space complexity O(n). We now look another sorting algorithm in the hope of Better.
Quick Sort
Depends on divide and conquer approach.
Check the slides where I showed the complete steps of quick sort with the help of an example.
6-1
6-2 Lecture 6: August 14
(
T (k) + T (n − k − 1) + cn if n > 1
T (n) =
c if n = 1
Worst Case : (
T (n − 1) + cn if n > 1
T (n) =
c if n = 1
Average Case : (
T (an) + T ((1 − a)n) + cn if n > 1
T (n) =
c if n = 1
where 0 < a < 1 is a constant representing the average split ratio.
Regardless of the exact value of a solving this recurrence relation still gives:
Worst case behavior occurs for the sorted array. Since we are using the last element of array as pivot, parti-
tion of array puts all elements in either at left or right.
In order to deal with it, we introduced the randomness on selecting the pivot element. We select the pivot
element uniformly at random among all possiblities. This new modified algorithm is called Randomised
Quick Sort.
However, the worst case behavior got reduced for many instances but still there are instances where time
complexity blow up to O(n2 ).
This can be easily checked that for any array of form [a,a,a,a . . . a], even randomised quick sort takes O(n2 )
time.
Space Complexity
We are not utilizing any additional space; therefore, the space we are utilizing is solely of the stack capacity.
The worst-case scenario is O(n), while the average case is O(log n).
Judgement Question
Is it possible to alter the randomized quick sort algorithm in such a way that the worst-case time
complexity becomes O(n log n)?