Professional Documents
Culture Documents
PPT3
PPT3
Week 3
Divide and Conquer
TextBooks
• Main Textbook
• S.Sridhar, 2015
Design and Analysis of Algorithm. Oxford
University. India.
ISBN: 978-0-19-809369-5
LEARNING OUTCOMES
• LO2 : Compare several algorithm design methods
OUTLINE
1. Introduction
2. Merge Sort
3. Quick Sort
4. Binary Search
INTRODUCTION
Introduction
• Given a function to compute on n inputs the divide and conquer
strategy suggest splitting the inputs into k distinct subsets
where 1 < k ≤ n and k is subproblem.
void Quick(A; p; r) {
//array A[p:r] split to A[p:q-1] and A[q+1:r]
if p ≥ r then return;
q = Partition(A, p, r);
Quick (A, p, q-1);
Quick (A, q+1, r);
}
Quick Sort Algorithm
int Partition(A; p; r) {
x = A[r];
i = p-1;
for(j=p; j ≤ r-1;j++)
if(A[j] ≤ x) {
i = i + 1;
Exchange(A[i+1], A[r]);
}
Exchange(A[i+1], A[r]);
return i+1;
}
Quick Sort Illustration
BINARY SEARCH
Search
• Suppose we have a series of numbers [2,45,8,9,32,15,27] and
want to find whether there are number 8 in a row.
• Sequential Search
o The most basic technique in the search
o The algorithm needs to check one by one the contents of the series and
compare it with the number 8 which sought
o Perform a search in order (sequence)
o If until the entire array have been compared and the data has not been
found, the search fails
o Sequential search is flexible because it can be used under any conditions, the
contents of the array should not be in a state of sequential
o Complexity Ο (n)
Binary Search
• Characteristics of Binary Search
Binary search techniques is searching data by Divide and Conquer technique.
- The contents of the array must be in a state of sequential/sorted
- Steps:
1. Suppose we'll find the data X in the array A
2. Define Ak where Ak is an element that is located right in the middle of the array A
3. If X = Ak, the data found set j = k
4. If X < Ak, then look to the left Ak,
do a recursive loop
5. If X > Ak, then look to the right Ak,
do a recursive loop
6. If X is not found set j = 0, the data does not exist
• Binary Search algorithm complexity is Ο(log2 n)
Binary Search Algorithm
1 A=[2,8,9,15,27,32,45]
2 display “Search X = ? "
3 read X
4 iLow=1
5 iHigh=N
6 j=0
7 while (j=0) and (iLow<=iHigh) do
8 iMid=(iLow+iHigh) div 2
9 if A[iMid]=X then
10 j=iMid
11 else if A[iMid]>X then
12 iHigh=iMid-1
13 else if A[iMid]<X then
14 iLow=iMid+1
15 end if
16 end while
17 if j>0 then
18 display “X = ",X," is found in index ", j
19 else
20 display ”X = ",X," is not found"
21 end if
Binary Search Illustration
References
• Levitin, A. (2012). The Introduction to The Design and Analysis
of Algorithms (3rd ed.). Pearson. Chapter
• Sridhar, S. (2015). Design and Analysis of Algorithms. Oxford
University Press. Chapter 8
• Divide & Conquer: Convex Hull, Median Finding,
www.youtube.com/watch?v=EzeYI7p9MjU