Quicksort: 7/11/2019 Mitra Kabir, Dept. of CSE, DU 1
Quicksort: 7/11/2019 Mitra Kabir, Dept. of CSE, DU 1
2. Conquer: The solution of the original problem is formed from the solutions
to the subproblems.
The running time equation of divide and conquer approach:
T(n) = 2T(n/2) + O(n) where n is the input size.
The solution to this equation is O(nlog2n).
Select pivot
13 81 10 43 31 75 0 92
Partition
13 10 0 31 81 43 75 92
Quicksort
0 10 13 31 43 75 81 92
Sorted List
0 10 13 31 43 75 81 92
20 80 70 10 60 50 7 30 40
Partitioning Array
Given a pivot, partition the elements of the array
such that the resulting array consists of:
1. One sub-array that contains elements >= pivot
2. Another sub-array that contains elements < pivot
i j
pivot_index = 0 20 80 70 10 60 50 7 30 40
[0] [1] [2] [3] [4] [5] [6] [7] [8]
i j
pivot_index = 0 20 80 70 10 60 50 7 30 40
[0] [1] [2] [3] [4] [5] [6] [7] [8]
i j
pivot_index = 0 20 80 70 10 60 50 7 30 40
[0] [1] [2] [3] [4] [5] [6] [7] [8]
i j
pivot_index = 0 20 80 70 10 60 50 7 30 40
[0] [1] [2] [3] [4] [5] [6] [7] [8]
i j
pivot_index = 0 20 10 70 80 60 50 7 30 40
[0] [1] [2] [3] [4] [5] [6] [7] [8]
i j
pivot_index = 0 20 10 70 80 60 50 7 30 40
[0] [1] [2] [3] [4] [5] [6] [7] [8]
i j
pivot_index = 0 20 10 70 80 60 50 7 30 40
[0] [1] [2] [3] [4] [5] [6] [7] [8]
i j
pivot_index = 0 20 10 70 80 60 50 7 30 40
[0] [1] [2] [3] [4] [5] [6] [7] [8]
i j
pivot_index = 0 20 10 7 80 60 50 70 30 40
[0] [1] [2] [3] [4] [5] [6] [7] [8]
i j
pivot_index = 0 20 10 7 80 60 50 70 30 40
[0] [1] [2] [3] [4] [5] [6] [7] [8]
i j
pivot_index = 0 20 10 7 30 60 50 70 80 40
[0] [1] [2] [3] [4] [5] [6] [7] [8]
i j
pivot_index = 0 20 10 7 30 40 50 70 80 60
[0] [1] [2] [3] [4] [5] [6] [7] [8]
i
Partition Result
20 10 7 30 40 50 70 80 60
[0] [1] [2] [3] [4] [5] [6] [7] [8]
20 10 7 30 40 50 70 80 60
[0] [1] [2] [3] [4] [5] [6] [7] [8]
2. Average Case:
The average running time of Quick sort is obtained by averaging the runtime
of all possible subproblems’ sizes. That means it occurs from the fact that on
average each reduction step of the algorithm produces two subsets. So, the
average running time is 0(NlogN).
3. Best Case:
The best case occurs when the partition always splits into two subsets with
equal number of elements. So, the running time is 0(NlogN).
7/11/2019 Mitra Kabir, Dept. of CSE, DU 26
END