Académique Documents
Professionnel Documents
Culture Documents
Quick Sort
CSE 2215 - Lecture 5 - Fall 2023
Instructor : Fahmid Al Rifat, Lecturer, Dept. of CSE , UIU
mohaiminul@cse.uiu.ac.bd 1
Divide & Conquer (revisited)
2
Divide-and-Conquer Technique
smaller
o instances of the same problem
o Conquer the subproblems by solving them recursively
o Combine the solutions to the subproblems into the solution for
the
o original problem
The base case for the recursion are subproblems of constant size
Analysis can be done using recurrence equations
3
Quick Sort
4
Divide-and-Conquer
5
Merge Sort and Quick Sort
Merge sort
o Divide step is trivial – just split the list into two equal parts.
o Work is carried out in the conquer step by merging two sorted lists.
Quicksort
o Work is carried out in the divide step using a pivot element.
o Conquer step is trivial.
6
Quick Sort
A[q+1..r]
p q q+1 r
8 15 4 30 25 7 18 12 8 4 7 12 15 30 25 18
Invariant: All elements in A[p..q] are less than all elements in A[q+1..r]
■ The subarrays are recursively sorted by calls to quicksort
array
Quick Sort
Quicksort -Simulation
10
Quicksort -Simulation
11
Quicksort -Simulation
12
Quicksort -Simulation
13
Quicksort -Simulation
14
Quicksort -Simulation
15
Quicksort -Simulation
16
Quicksort -Simulation
17
Quicksort -Simulation
18
Quicksort -Simulation
19
Quicksort -Simulation
20
Quicksort -Simulation
21
Quicksort -Simulation
22
Quick Sort (Partition)
■ End result:
Two subarrays
All values in first subarray | pivot | all values in the second subarray
■ Returns the index of the “pivot” element separating the two subarrays
Quick Sort (Analysis)
The recurrence for the worst-case running time T(n) is [Partition is always
unbalanced]
Quick Sort: Best case running time
The recurrence for the best-case running time T(n) is [Partition is always
balanced]
Quick Sort: Running Time
Quick Sort: Analysis
29