Week 6
Week 6
ANALYSIS OF
ALGORITHMS
Course Code : AR212
Credit Hours :3
Prerequisite : AR211
Instructor Information
[Pre-req. AR211
Textbook: Introduction to Algorithms, Thomas Cormen, Charls Leiserson & Ronald Rivest. 3rd Edition,
MIT Press, 2009.
So check if any number > pivot send it on the right side and if any number < pivot send it on the left side
increment i until you find an element > 10 and decrement j until you find element < 10 swap them
10 16 8 12 15 6 3 9 5 22
i j
10 5 8 12 15 6 3 9 16 22
10 5 8 12 15 6 3 9 16 22
i j
Example on PartitionAlgorithm
10 5 8 9 15 6 3 12 16 22
10 5 8 9 15 6 3 12 16 22
i j
10 5 8 9 3 6 15 12 16 22
10 5 8 9 3 6 15 12 16 22
j i
j < i stop swap the pivot with
6 A[j]
5 8 9 3 10 15 12 16 22
pivot
< pivot > pivot
Animated Gif forpartitioning
int Partition(int a[], int low, int high)
{
int pivot = Partition
a[low]; int i = low
;int j = high+1 ; Algorith
while(1)
{ m
do {
i++;
} while (a[i] < pivot);
do {
j--;
} while (a[j] > pivot);
if(i >= j)
return j;
swap(a[i], a[j]);
}
}
Quick SortAnalysis
• The time complexity of quick sort depends directly on the :
1) The location of the pivot
2) The state of the array
Worst CasePartitioning
• At every step, partition() splits the array as unequally as possible ( k
= 1 or k = n).
• the worst occurs in following cases.
1) Array is already sorted in same order.
2) Array is already sorted in reverse order.
SortedArr
ay
Worst CasePartitioning
Best CasePartitioning
• The best case occurs :
• when the partition process always picks the middle element as pivot.
• Every time the size of the two subarrays are equal.
Best CasePartitioning
ChoosingPiv
ot
• Do not choose the first element of A because if the array is originally
nearly sorted or reversed sorted, All the elements will go to only
one partition.
• Choose the pivot randomly.
• Another way is to choose the median value from the first, the
last, and the middle element of the array. sort them then
choose middle as pivot.
Merge SortVs.Quick
Sort
BASIS FOR COMPARISON QUICK SORT MERGE SORT
Partitioning of the elements The splitting of a list of Array is always divided into
in the array elements is not necessarily half (n/2).
divided into half.
2
Worst case complexity O(n ) O(n log n)