Quick Sort
& Quick Select
Today’s checklist
1. Quick Sort Algorithm
2. Quick Sort Time and Space Complexity
3. Randomised Pivot point
4. Stability
5. Quick Select Algorithm and kth Smallest/Largest
QuickSort Algorithm
lo hi
arr = 2 4 ,
9 ,
7 ,
1
,
2
,
3
,
6, 5 , 83
d
3 6, 5 8
9 ,
7 , 4 ,
2
, , ,
↓
lo hi lo hi
- I 3 247
↑
9
d
G
d
↓
magic magic
j
correctdx
QuickSort Algorithm lotscount
I
I 3 2 Co d hi
- 9 G S 8
I
2
Es 6 7
*
i
3 2
j
23
scount = E
Partition Algorithm
Code
For Each level ,
wi
operations are
performed
Time and Space complexity
lo hi
I
arr = 2 4 ,
9 ,
7 ,
1
,
2
,
3
,
6, 5 , 83
d
3 6, 5 8
9 ,
7 , 4 ,
2
, , ,
↓
lo hi lo hi
- I 3 247 9
d
G
d
j
magic magic
j
hi calls
At Max itni
/n logn)
*
0
Arg. Case =
↑ lagti
space Complexity : Recursive call stack space -
E
O(logn)
Worst Case TC
·otsa
↓
the no -
of levels here are not
'logn they are n
of Ops
No -
~n +n + n ... I
I n
<
+) ~ Out ⑤ T &
Esc
O(n)
Randomized Pivot point
I
Instead of choosing avrilof as pirot ,
we can choose
arr[thi] as
pirot
123638
d
④3658
d
3 > 658
Worst Case
& T-C S C
.
*
S
i
j
onlogn) O(logn)
Stability of Quick Sort
↓
Unstable
4 + / 23 S 18
Y
Y 97/ 2 3 S 8
-
-
* 4 7 S 9 8
1 3
2
Merge Sort vs Quick Sort
↓ ↓
worst case is more
space optimised
better
Stable
Ques: n = 7
smallest
Q : Kth Largest Element in an Array.
kt largest
Y 9 7 I 2 3 6
(n- 1)
=
av
d
= x+ smallest
I a 7 M 2 3 6
& 3 2 Y 7 9 6
- n
I 3 2
K = 2
3 2
2 B [Leetcode 215]
2( I
Ques: 1 4
+
.
+ +
= zu [1 ++ + 5 ....
]
Q : Kth Largest Element in an Array.
4
-
T -
+-
TC. =
0 (n) [Best & Arg Case]
&
O(n2 Worst Case < 4 [Leetcode 215]
Onlogn)
THANK YOU