Quick Sort-Protected-1 - Unlocked
Quick Sort-Protected-1 - Unlocked
Quicksort
Bachelor of Technology
CSE (AIML)/ICT
• Follows the divide-and-conquer paradigm.
• Divide: Partition (divide) the array A[p..r] into two (possibly empty) sub-arrays A[p..q–1] and
Analysis and Design of Algorithms A[q+1..r] such that:
Each element in A[p..q–1] ≤ A[q] ≤ each element in A[q+1..r]
Module 1 - Introduction
Quicksort Index q is computed as part of the partitioning procedure.
• Conquer: Sort the two sub-arrays by recursive calls to quicksort.
• Combine: The sub-arrays are sorted in place – no work is needed to combine them.
Dr. Anuj Kr. Singh
Associate Professor • How the divide and combine steps of quicksort can be compared with those of merge sort?
Computer Science & Engineering
Example 2 8 7 1 3 6 4 PARTITION(A, p, r)
QUICKSORT(A, p, r) PARTITION(A, p, r) 1 x = A[r]
1 if p < r then 1 x = A[r] // Pivot Element 2 i=p–1
2 i=p–1 3 for j = p to r – 1 do
2 q = PARTITION(A, p, r) // Divide
4 if A[j] x then
3 QUICKSORT(A, p, q – 1) // Conquer 3 for j = p to r – 1 do
5 i=i+1
4 QUICKSORT(A, q + 1, r) // Conquer 4 if A[j] x then 6 A[i] A[j] //Swapping
5 i=i+1 7 A[i + 1] A[r] //Swapping
6 A[i] A[j] //Swapping 8 return i + 1
12-09-2023 Dr. Anuj Kr. Singh, Associate Professor 3 12-09-2023 Dr. Anuj Kr. Singh, Associate Professor 4
12-09-2023
Worst Case
Average Case
12-09-2023 Dr. Anuj Kr. Singh, Associate Professor 5 12-09-2023 Dr. Anuj Kr. Singh, Associate Professor 6
Best Case When the partitioning element is placed at the middle of the array Worst Case When the partitioning element is placed at any one corner of the
Partitioning 01 every time. 02 array every time.
Partitioning
12-09-2023 Dr. Anuj Kr. Singh, Associate Professor 7 12-09-2023 Dr. Anuj Kr. Singh, Associate Professor 8
12-09-2023
Average Case When the partitioning element is placed neither at the middle not
Partitioning 03 at any corner of the array every time.
T(n) = 2 T(n/2) + n - Best case
12-09-2023 Dr. Anuj Kr. Singh, Associate Professor 9 12-09-2023 Dr. Anuj Kr. Singh, Associate Professor 10
RANDOMIZED-PARTITION(A, p, r)
return F(n-1)+F(n-2) • Works for sorted arrays
1 i = RANDOM [p, r] • A Divide and Conquer Algorithm.
2 A[i ] A[r] • Has running time of order lg n.
3 return PARTITION (A, p, r)
Example
2 8 7 1 3 6 4
12-09-2023 Dr. Anuj Kr. Singh, Associate Professor 11 12-09-2023 Dr. Anuj Kr. Singh, Associate Professor 12
12-09-2023
Two Medians
• The minimum of a set of elements is the Unique Median 𝑖 = 𝑛/2
first order statistic (i = 1),and the 𝑖 = (𝑛 + 1)/2 𝑛
𝑖 = +1 • Simultaneous minimum and maximum
maximum is the nth order statistic (i = n). 2
12-09-2023 Dr. Anuj Kr. Singh, Associate Professor 13 12-09-2023 Dr. Anuj Kr. Singh, Associate Professor 14