Quick Sort
Quick Sort
QUICK SORT
Hina Nawaz
QUICK SORT
Quick Sort follows the divide and conquer
approach.
Divide and conquer is a technique of breaking
down the algorithms into sub problems, then
solving the sub problems, and combining the
results back together to solve the original
problem
QUICK SORT
1) An array is divided into subarrays by selecting
a pivot element (element selected from the
array).
5 3 7 6 1 2 4
QUICK SORT
5 3 7 6 1 2 4
left right
5 3 7 6 1 2 4
left right
5 3 7 6 1 2 4
left right
5 3 7 6 1 2 4
left right
J < Pivot
5<4 F
QUICK SORT i = left - 1
i= -1
j pivot
5 3 7 6 1 2 4
left right
J < Pivot
3<4 T
QUICK SORT i = left - 1
i= -1
j pivot
5 3 7 6 1 2 4
left right
Condition is true
Increment I
Swap value of i with j
QUICK SORT i = -1 + 1
i= 0
i j pivot
5 3 7 6 1 2 4
left right
Condition is true
Increment I
Swap value of i with j
QUICK SORT i = -1 + 1
i= 0
i j pivot
3 5 7 6 1 2 4
left right
QUICK SORT i = -1 + 1
i= 0
i j pivot
3 5 7 6 1 2 4
left right
J < Pivot
7<4 F
QUICK SORT i = -1 + 1
i= 0
i j pivot
3 5 7 6 1 2 4
left right
J < Pivot
6<4 F
QUICK SORT i = -1 + 1
i= 0
i j pivot
3 5 7 6 1 2 4
left right
J < Pivot
1<4 T
QUICK SORT i = -1 + 1
i= 0
i j pivot
3 5 7 6 1 2 4
left right
Condition is true
Increment I
Swap value of i with j
QUICK SORT i=0+1
i= 1
i j pivot
3 5 7 6 1 2 4
left right
Condition is true
Increment I
Swap value of i with j
QUICK SORT i= 1
i j pivot
3 1 7 6 5 2 4
left right
QUICK SORT i=1
i j pivot
3 1 7 6 5 2 4
left right
J < Pivot
2<4 T
QUICK SORT i=1
i j pivot
3 1 7 6 5 2 4
left right
Condition is true
Increment I
Swap value of i with j
QUICK SORT i=1+1
i=2
i j pivot
3 1 7 6 5 2 4
left right
Condition is true
Increment I
Swap value of i with j
QUICK SORT i=1+1
i=2
i j pivot
3 1 2 6 5 7 4
left right
QUICK SORT i=1+1
i=2
i j pivot
3 1 2 6 5 7 4
left right
End for
swap arr[i + 1] with arr[right]
QUICK SORT i=2
i i+1 j pivot
3 1 2 6 5 7 4
left right
End for
swap arr[i + 1] with arr[right]
QUICK SORT i=2
i i+1 j pivot
3 1 2 4 5 7 6
left right
End for
swap arr[i + 1] with arr[right]
QUICK SORT
3 1 2 4 5 7 6
0 1 2 3 4 5 6
QUICK SORT
3 1 2 4 5 7 6
QUICK SORT
pIndex = 3
4
Quick Sort Quick Sort
3 1 2 5 7 6
0 1 2 4 5 6
ALGORITHM
Quicksort(array, left, right)
{
pivot = arr[right]; // Setting rightmost Index as pivot
pivot
O(n)
n1 n2
n1 n2
Best Case
n/2 n/2
= 2T(n/2)+n
= n log n
TIME COMPLEXITY
Average Case
1 2 3 4 5 6
TIME COMPLEXITY
Worst Case
pivot
1 2 3 4 5 6
pivot
1 2 3 4 5 6
TIME COMPLEXITY
Worst Case
0 n-1
0 n-2
.
.
1
TIME COMPLEXITY
Worst Case
= 0 + T(n-1)+n
O(n2)
TIME COMPLEXITY
Best Case:
O(n*log n)
Worst Case:
O(n2)
Average Case:
O(n*log n)