Professional Documents
Culture Documents
(Serial Manner)
Week 13 – Lecture 37
Introduction
As the name refers, the quicksort is quick! It can perform two to three times faster
than merge sort and heap sort.
It is a comparison sorting algorithm that acquires the Divide and Conquer
approach.
How Quick Sort Works?
Pivot
Partition 1 Partition 2
Element
Pivot
Partition 1 Partition 2
Element
Step 1: Divide
In this step at first, we choose a pivot. A pivot is any
element from the array or subarray. we’ll choose the
leftmost element from a subarray as the pivot. After
choosing the pivot we’ll rearrange the elements so that all
the elements that are less than or equal to the pivot are to
its left and the elements that are greater than the pivot are
to its right. This procedure is called partitioning. After
partitioning the pivot is in its final position.
Example (Cont.…..)
Let’s take two variables named “Start” and “End”
7 6 10 5 9 2 1 15 7
Start End
7 6 10 5 9 2 1 15 7
Start End
7 6 10 5 9 2 1 15 7
Start End
7 6 10 5 9 2 1 15 7
Start End
7 6 10 5 9 2 1 15 7
7 6 7 5 9 2 1 15 10
Start End
Example (Cont.…..)
We have to Swap “Start with End”
Swa
p
7 6 10 5 9 2 1 15 7
7 6 7 5 9 2 1 15 10
Start End
Example (Cont.…..)
We have to Swap “Start with End”
Swa
p
7 6 10 5 9 2 1 15 7
7 6 7 5 9 2 1 15 10
7 6 10 5 9 2 1 15 7
7 6 7 5 9 2 1 15 10
Start End
Example (Cont.…..)
We have to Swap “Start with End”
Swa
p
7 6 10 5 9 2 1 15 7
7 6 7 5 9 2 1 15 10
7 6 10 5 9 2 1 15 7
Swa
p
7 6 7 5 9 2 1 15 10
1 9
Start End
Example (Cont.…..)
We have to Swap “Start with End”
7 6 10 5 9 2 1 15 7
Swa
p
7 6 7 5 9 2 1 15 10
1 9
7 6 10 5 9 2 1 15 7
Swa
p
7 6 7 5 9 2 1 15 10
1 9
NOTE: When both “Start and
End” have crossed each other
then we will never swap them.
We’ll swap “Pivot with End”
End Star
with each other.
Example (Cont.…..)
All the elements on the left of the pivot are smaller and those on the right are
larger.
2 7
Now, the pivot is in its right position and you will apply the same strategy to the
newly generated partitions.
Code for This Dry Run
Partition Function
Partition (A, lb, ub) {
Quicksort Algorithm
Pivot = A[lb];
Quicksort( A, lb, ub) {
Start = lb;
If (lb < ub) {
End = ub;
loc = Partition (A, lb, ub);
while (A[Start] <= Pivot) {
Quicksort( A, lb, loc - 1);
Start++; }
Quicksort( A, loc + 1, ub);
while (A[End] > Pivot) {
}
End--; }
}
If (Start < End) {
Swap (A[Start], A[End]); }
Else {
Swap (A[lb], A[End]);
Return End;
}