SlideShare a Scribd company logo
UNIT III
Searching and Sorting
Searching
• Given a collection and an element (key) to
find…
• Output
– Print a message (“Found”, “Not Found)
– Return a value (position of key )
Linear Search: A Simple Search
• A search traverses the collection until
– The desired element is found
– Or the collection is exhausted
• If the collection is ordered, I might not
have to look at all elements
– I can stop looking when I know the
element cannot be in the collection.
Iterative Array Search
procedure Search(my_array Array,
target Num)
i Num
i <- 1
loop for (i=0;i <MAX ;i++)
if(a[i]==target)
print(“Target data found”)
break;
endloop
if(i > MAX) then
print(“Target data not found”)
endif
endprocedure // Search
my_array
7 12 5 22 13 32
1 2 3 4 5 6
target = 13
procedure Search(my_array Array,
target Num)
i Num
i <- 1
loop for (i=0;i <MAX ;i++)
if(a[i]==target)
print(“Target data found”)
break;
endloop
if(i > MAX) then
print(“Target data not found”)
endif
endprocedure // Search
procedure Search(my_array isoftype in NumArrayType,
target isoftype in Num)
i isoftype Num
i <- 1
loop
exitif((i > MAX) OR (my_array[i] = target))
i <- i + 1
endloop
if(i > MAX) then
print(“Target data not found”)
else
print(“Target data found”)
endif
endprocedure // Search
my_array
7 12 5 22 13 32
1 2 3 4 5 6
target = 13
procedure Search(my_array isoftype in NumArrayType,
target isoftype in Num)
i isoftype Num
i <- 1
loop
exitif((i > MAX) OR (my_array[i] = target))
i <- i + 1
endloop
if(i > MAX) then
print(“Target data not found”)
else
print(“Target data found”)
endif
endprocedure // Search
my_array
7 12 5 22 13 32
1 2 3 4 5 6
target = 13
procedure Search(my_array isoftype in NumArrayType,
target isoftype in Num)
i isoftype Num
i <- 1
loop
exitif((i > MAX) OR (my_array[i] = target))
i <- i + 1
endloop
if(i > MAX) then
print(“Target data not found”)
else
print(“Target data found”)
endif
endprocedure // Search
my_array
7 12 5 22 13 32
1 2 3 4 5 6
target = 13
procedure Search(my_array isoftype in NumArrayType,
target isoftype in Num)
i isoftype Num
i <- 1
loop
exitif((i > MAX) OR (my_array[i] = target))
i <- i + 1
endloop
if(i > MAX) then
print(“Target data not found”)
else
print(“Target data found”)
endif
endprocedure // Search
my_array
7 12 5 22 13 32
1 2 3 4 5 6
target = 13
procedure Search(my_array isoftype in NumArrayType,
target isoftype in Num)
i isoftype Num
i <- 1
loop
exitif((i > MAX) OR (my_array[i] = target))
i <- i + 1
endloop
if(i > MAX) then
print(“Target data not found”)
else
print(“Target data found”)
endif
endprocedure // Search
my_array
7 12 5 22 13 32
1 2 3 4 5 6
target = 13
procedure Search(my_array isoftype in NumArrayType,
target isoftype in Num)
i isoftype Num
i <- 1
loop
exitif((i > MAX) OR (my_array[i] = target))
i <- i + 1
endloop
if(i > MAX) then
print(“Target data not found”)
else
print(“Target data found”)
endif
endprocedure // Search
my_array
7 12 5 22 13 32
1 2 3 4 5 6
target = 13
procedure Search(my_array isoftype in NumArrayType,
target isoftype in Num)
i isoftype Num
i <- 1
loop
exitif((i > MAX) OR (my_array[i] = target))
i <- i + 1
endloop
if(i > MAX) then
print(“Target data not found”)
else
print(“Target data found”)
endif
endprocedure // Search
my_array
7 12 5 22 13 32
1 2 3 4 5 6
target = 13
Target data found
procedure Search(my_array isoftype in NumArrayType,
target isoftype in Num)
i isoftype Num
i <- 1
loop
exitif((i > MAX) OR (my_array[i] = target))
i <- i + 1
endloop
if(i > MAX) then
print(“Target data not found”)
else
print(“Target data found”)
endif
endprocedure // Search
my_array
7 12 5 22 13 32
1 2 3 4 5 6
target = 13
Linear Search Analysis: Best Case
procedure Search(my_array Array,
target Num)
i Num
i <- 1
loop
exitif((i > MAX) OR (my_array[i] = target))
i <- i + 1
endloop
if(i > MAX) then
print(“Target data not found”)
else
print(“Target data found”)
endif
endprocedure // Search
Scan the array
Best Case: match with the first item
7 12 5 22 13 32
target = 7
Best Case:
1 comparison
Linear Search Analysis: Worst Case
procedure Search(my_array Array,
target Num)
i Num
i <- 1
loop
exitif((i > MAX) OR (my_array[i] = target))
i <- i + 1
endloop
if(i > MAX) then
print(“Target data not found”)
else
print(“Target data found”)
endif
endprocedure // Search
Scan the array
Worst Case: match with the last item (or no match)
7 12 5 22 13 32
target = 32
Worst Case:
N comparisons
Binary Search
The Scenario
• We have a sorted array
• We want to determine if a particular element is in the array
– Once found, print or return (index, boolean, etc.)
– If not found, indicate the element is not in the collection
7 12 42 59 71 86 104 212
A Better Search Algorithm
• Of course we could use our simpler search
and traverse the array
• But we can use the fact that the array is
sorted to our advantage
• This will allow us to reduce the number of
comparisons
Binary Search
• Requires a sorted array or a binary search tree.
• Cuts the “search space” in half each time.
• Keeps cutting the search space in half until the
target is found or has exhausted the all possible
locations.
Binary Search Algorithm
look at “middle” element
if no match then
look left (if need smaller) or
right (if need larger)
1 7 9 12 33 42 59 76 81 84 91 92 93 99
Look for 42
The Algorithm
look at “middle” element
if no match then
look left or right
1 7 9 12 33 42 59 76 81 84 91 92 93 99
Look for 42
The Algorithm
look at “middle” element
if no match then
look left or right
1 7 9 12 33 42 59 76 81 84 91 92 93 99
Look for 42
The Algorithm
look at “middle” element
if no match then
look left or right
1 7 9 12 33 42 59 76 81 84 91 92 93 99
Look for 42
The Binary Search Algorithm
• Return found or not found (true or false), so it should
be a function.
• When move left or right, change the array boundaries
– We’ll need a first and last
The Binary Search Algorithm
calculate middle position
if (first and last have “crossed”) then
“Item not found”
elseif (element at middle = to_find) then
“Item Found”
elseif to_find < element at middle then
Look to the left
else
Look to the right
Looking Left
• Use indices “first” and “last” to keep track of
where we are looking
• Move left by setting last = middle – 1
7 12 42 59 71 86 104 212
F L
M
L
Looking Right
• Use indices “first” and “last” to keep track of
where we are looking
• Move right by setting first = middle + 1
7 12 42 59 71 86 104 212
F L
M F
Binary Search Example – Found
7 12 42 59 71 86 104 212
Looking for 42
F L
M
Binary Search Example – Found
7 12 42 59 71 86 104 212
Looking for 42
F L
M
Binary Search Example – Found
7 12 42 59 71 86 104 212
42 found – in 3 comparisons
F
L
M
Binary Search Example – Not Found
7 12 42 59 71 86 104 212
Looking for 89
F L
M
Binary Search Example – Not Found
7 12 42 59 71 86 104 212
Looking for 89
F L
M
Binary Search Example – Not Found
7 12 42 59 71 86 104 212
Looking for 89
F L
M
Binary Search Example – Not Found
7 12 42 59 71 86 104 212
89 not found – 3 comparisons
F
L
Function Find return boolean (A Array, first, last, to_find)
middle <- (first + last) div 2
if (first > last) then
return false
elseif (A[middle] = to_find) then
return true
elseif (to_find < A[middle]) then
return Find(A, first, middle–1, to_find)
else
return Find(A, middle+1, last, to_find)
endfunction
Binary Search Function
Binary Search Analysis: Best Case
Function Find return boolean (A Array, first, last, to_find)
middle <- (first + last) div 2
if (first > last) then
return false
elseif (A[middle] = to_find) then
return true
elseif (to_find < A[middle]) then
return Find(A, first, middle–1, to_find)
else
return Find(A, middle+1, last, to_find)
endfunction
Best Case: match from the firs comparison
Best Case:
1 comparison
1 7 9 12 33 42 59 76 81 84 91 92 93 99
Target: 59
Binary Search Analysis: Worst Case
Function Find return boolean (A Array, first, last, to_find)
middle <- (first + last) div 2
if (first > last) then
return false
elseif (A[middle] = to_find) then
return true
elseif (to_find < A[middle]) then
return Find(A, first, middle–1, to_find)
else
return Find(A, middle+1, last, to_find)
endfunction
Worst Case: divide until reach one item, or no match.
1 7 9 12 33 42 59 76 81 84 91 92 93 99
How many
comparisons??
Binary Search Analysis: Worst Case
• With each comparison we throw away ½ of the list
N
N/2
N/4
N/8
1
………… 1 comparison
………… 1 comparison
………… 1 comparison
………… 1 comparison
………… 1 comparison
.
.
.
Number of steps is at
most Log2N
Summary
• Binary search reduces the work by half at each
comparison
• If array is not sorted  Linear Search
– Best Case O(1)
– Worst Case O(N)
• If array is sorted  Binary search
– Best Case O(1)
– Worst Case O(Log2N)

More Related Content

Similar to Searching.ppt

Algorithm & data structures lec4&5
Algorithm & data structures lec4&5Algorithm & data structures lec4&5
Algorithm & data structures lec4&5
Abdul Khan
 
In the binary search, if the array being searched has 32 elements in.pdf
In the binary search, if the array being searched has 32 elements in.pdfIn the binary search, if the array being searched has 32 elements in.pdf
In the binary search, if the array being searched has 32 elements in.pdf
arpitaeron555
 
Algorithm 8th lecture linear & binary search(2).pptx
Algorithm 8th lecture linear & binary search(2).pptxAlgorithm 8th lecture linear & binary search(2).pptx
Algorithm 8th lecture linear & binary search(2).pptx
Aftabali702240
 

Similar to Searching.ppt (20)

Unit 6 dsa SEARCHING AND SORTING
Unit 6 dsa SEARCHING AND SORTINGUnit 6 dsa SEARCHING AND SORTING
Unit 6 dsa SEARCHING AND SORTING
 
searching in data structure.pptx
searching in data structure.pptxsearching in data structure.pptx
searching in data structure.pptx
 
Algorithm & data structures lec4&5
Algorithm & data structures lec4&5Algorithm & data structures lec4&5
Algorithm & data structures lec4&5
 
Linear and Binary Search
Linear and Binary SearchLinear and Binary Search
Linear and Binary Search
 
Unit 7 sorting
Unit   7 sortingUnit   7 sorting
Unit 7 sorting
 
Unit 8 searching and hashing
Unit   8 searching and hashingUnit   8 searching and hashing
Unit 8 searching and hashing
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3
 
Rahat &amp; juhith
Rahat &amp; juhithRahat &amp; juhith
Rahat &amp; juhith
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and Searching
 
Chapter 11 ds
Chapter 11 dsChapter 11 ds
Chapter 11 ds
 
advanced searching and sorting.pdf
advanced searching and sorting.pdfadvanced searching and sorting.pdf
advanced searching and sorting.pdf
 
sorting and searching.pptx
sorting and searching.pptxsorting and searching.pptx
sorting and searching.pptx
 
1 class linear and Binary search (3).ppt
1 class linear and Binary search (3).ppt1 class linear and Binary search (3).ppt
1 class linear and Binary search (3).ppt
 
Dsa – data structure and algorithms searching
Dsa – data structure and algorithms   searchingDsa – data structure and algorithms   searching
Dsa – data structure and algorithms searching
 
In the binary search, if the array being searched has 32 elements in.pdf
In the binary search, if the array being searched has 32 elements in.pdfIn the binary search, if the array being searched has 32 elements in.pdf
In the binary search, if the array being searched has 32 elements in.pdf
 
Algorithm and Programming (Searching)
Algorithm and Programming (Searching)Algorithm and Programming (Searching)
Algorithm and Programming (Searching)
 
searching
searchingsearching
searching
 
Searching
Searching Searching
Searching
 
PPT.pptx Searching and Sorting Techniques
PPT.pptx Searching and Sorting TechniquesPPT.pptx Searching and Sorting Techniques
PPT.pptx Searching and Sorting Techniques
 
Algorithm 8th lecture linear & binary search(2).pptx
Algorithm 8th lecture linear & binary search(2).pptxAlgorithm 8th lecture linear & binary search(2).pptx
Algorithm 8th lecture linear & binary search(2).pptx
 

Recently uploaded

678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 

Recently uploaded (20)

678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.pptBasic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
Benefits and Challenges of Using Open Educational Resources
Benefits and Challenges of Using Open Educational ResourcesBenefits and Challenges of Using Open Educational Resources
Benefits and Challenges of Using Open Educational Resources
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
B.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdfB.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdf
 
NLC-2024-Orientation-for-RO-SDO (1).pptx
NLC-2024-Orientation-for-RO-SDO (1).pptxNLC-2024-Orientation-for-RO-SDO (1).pptx
NLC-2024-Orientation-for-RO-SDO (1).pptx
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 

Searching.ppt

  • 2. Searching • Given a collection and an element (key) to find… • Output – Print a message (“Found”, “Not Found) – Return a value (position of key )
  • 3. Linear Search: A Simple Search • A search traverses the collection until – The desired element is found – Or the collection is exhausted • If the collection is ordered, I might not have to look at all elements – I can stop looking when I know the element cannot be in the collection.
  • 4. Iterative Array Search procedure Search(my_array Array, target Num) i Num i <- 1 loop for (i=0;i <MAX ;i++) if(a[i]==target) print(“Target data found”) break; endloop if(i > MAX) then print(“Target data not found”) endif endprocedure // Search
  • 5. my_array 7 12 5 22 13 32 1 2 3 4 5 6 target = 13 procedure Search(my_array Array, target Num) i Num i <- 1 loop for (i=0;i <MAX ;i++) if(a[i]==target) print(“Target data found”) break; endloop if(i > MAX) then print(“Target data not found”) endif endprocedure // Search
  • 6. procedure Search(my_array isoftype in NumArrayType, target isoftype in Num) i isoftype Num i <- 1 loop exitif((i > MAX) OR (my_array[i] = target)) i <- i + 1 endloop if(i > MAX) then print(“Target data not found”) else print(“Target data found”) endif endprocedure // Search my_array 7 12 5 22 13 32 1 2 3 4 5 6 target = 13
  • 7. procedure Search(my_array isoftype in NumArrayType, target isoftype in Num) i isoftype Num i <- 1 loop exitif((i > MAX) OR (my_array[i] = target)) i <- i + 1 endloop if(i > MAX) then print(“Target data not found”) else print(“Target data found”) endif endprocedure // Search my_array 7 12 5 22 13 32 1 2 3 4 5 6 target = 13
  • 8. procedure Search(my_array isoftype in NumArrayType, target isoftype in Num) i isoftype Num i <- 1 loop exitif((i > MAX) OR (my_array[i] = target)) i <- i + 1 endloop if(i > MAX) then print(“Target data not found”) else print(“Target data found”) endif endprocedure // Search my_array 7 12 5 22 13 32 1 2 3 4 5 6 target = 13
  • 9. procedure Search(my_array isoftype in NumArrayType, target isoftype in Num) i isoftype Num i <- 1 loop exitif((i > MAX) OR (my_array[i] = target)) i <- i + 1 endloop if(i > MAX) then print(“Target data not found”) else print(“Target data found”) endif endprocedure // Search my_array 7 12 5 22 13 32 1 2 3 4 5 6 target = 13
  • 10. procedure Search(my_array isoftype in NumArrayType, target isoftype in Num) i isoftype Num i <- 1 loop exitif((i > MAX) OR (my_array[i] = target)) i <- i + 1 endloop if(i > MAX) then print(“Target data not found”) else print(“Target data found”) endif endprocedure // Search my_array 7 12 5 22 13 32 1 2 3 4 5 6 target = 13
  • 11. procedure Search(my_array isoftype in NumArrayType, target isoftype in Num) i isoftype Num i <- 1 loop exitif((i > MAX) OR (my_array[i] = target)) i <- i + 1 endloop if(i > MAX) then print(“Target data not found”) else print(“Target data found”) endif endprocedure // Search my_array 7 12 5 22 13 32 1 2 3 4 5 6 target = 13
  • 12. procedure Search(my_array isoftype in NumArrayType, target isoftype in Num) i isoftype Num i <- 1 loop exitif((i > MAX) OR (my_array[i] = target)) i <- i + 1 endloop if(i > MAX) then print(“Target data not found”) else print(“Target data found”) endif endprocedure // Search my_array 7 12 5 22 13 32 1 2 3 4 5 6 target = 13 Target data found
  • 13. procedure Search(my_array isoftype in NumArrayType, target isoftype in Num) i isoftype Num i <- 1 loop exitif((i > MAX) OR (my_array[i] = target)) i <- i + 1 endloop if(i > MAX) then print(“Target data not found”) else print(“Target data found”) endif endprocedure // Search my_array 7 12 5 22 13 32 1 2 3 4 5 6 target = 13
  • 14. Linear Search Analysis: Best Case procedure Search(my_array Array, target Num) i Num i <- 1 loop exitif((i > MAX) OR (my_array[i] = target)) i <- i + 1 endloop if(i > MAX) then print(“Target data not found”) else print(“Target data found”) endif endprocedure // Search Scan the array Best Case: match with the first item 7 12 5 22 13 32 target = 7 Best Case: 1 comparison
  • 15. Linear Search Analysis: Worst Case procedure Search(my_array Array, target Num) i Num i <- 1 loop exitif((i > MAX) OR (my_array[i] = target)) i <- i + 1 endloop if(i > MAX) then print(“Target data not found”) else print(“Target data found”) endif endprocedure // Search Scan the array Worst Case: match with the last item (or no match) 7 12 5 22 13 32 target = 32 Worst Case: N comparisons
  • 17. The Scenario • We have a sorted array • We want to determine if a particular element is in the array – Once found, print or return (index, boolean, etc.) – If not found, indicate the element is not in the collection 7 12 42 59 71 86 104 212
  • 18. A Better Search Algorithm • Of course we could use our simpler search and traverse the array • But we can use the fact that the array is sorted to our advantage • This will allow us to reduce the number of comparisons
  • 19. Binary Search • Requires a sorted array or a binary search tree. • Cuts the “search space” in half each time. • Keeps cutting the search space in half until the target is found or has exhausted the all possible locations.
  • 20. Binary Search Algorithm look at “middle” element if no match then look left (if need smaller) or right (if need larger) 1 7 9 12 33 42 59 76 81 84 91 92 93 99 Look for 42
  • 21. The Algorithm look at “middle” element if no match then look left or right 1 7 9 12 33 42 59 76 81 84 91 92 93 99 Look for 42
  • 22. The Algorithm look at “middle” element if no match then look left or right 1 7 9 12 33 42 59 76 81 84 91 92 93 99 Look for 42
  • 23. The Algorithm look at “middle” element if no match then look left or right 1 7 9 12 33 42 59 76 81 84 91 92 93 99 Look for 42
  • 24. The Binary Search Algorithm • Return found or not found (true or false), so it should be a function. • When move left or right, change the array boundaries – We’ll need a first and last
  • 25. The Binary Search Algorithm calculate middle position if (first and last have “crossed”) then “Item not found” elseif (element at middle = to_find) then “Item Found” elseif to_find < element at middle then Look to the left else Look to the right
  • 26. Looking Left • Use indices “first” and “last” to keep track of where we are looking • Move left by setting last = middle – 1 7 12 42 59 71 86 104 212 F L M L
  • 27. Looking Right • Use indices “first” and “last” to keep track of where we are looking • Move right by setting first = middle + 1 7 12 42 59 71 86 104 212 F L M F
  • 28. Binary Search Example – Found 7 12 42 59 71 86 104 212 Looking for 42 F L M
  • 29. Binary Search Example – Found 7 12 42 59 71 86 104 212 Looking for 42 F L M
  • 30. Binary Search Example – Found 7 12 42 59 71 86 104 212 42 found – in 3 comparisons F L M
  • 31. Binary Search Example – Not Found 7 12 42 59 71 86 104 212 Looking for 89 F L M
  • 32. Binary Search Example – Not Found 7 12 42 59 71 86 104 212 Looking for 89 F L M
  • 33. Binary Search Example – Not Found 7 12 42 59 71 86 104 212 Looking for 89 F L M
  • 34. Binary Search Example – Not Found 7 12 42 59 71 86 104 212 89 not found – 3 comparisons F L
  • 35. Function Find return boolean (A Array, first, last, to_find) middle <- (first + last) div 2 if (first > last) then return false elseif (A[middle] = to_find) then return true elseif (to_find < A[middle]) then return Find(A, first, middle–1, to_find) else return Find(A, middle+1, last, to_find) endfunction Binary Search Function
  • 36. Binary Search Analysis: Best Case Function Find return boolean (A Array, first, last, to_find) middle <- (first + last) div 2 if (first > last) then return false elseif (A[middle] = to_find) then return true elseif (to_find < A[middle]) then return Find(A, first, middle–1, to_find) else return Find(A, middle+1, last, to_find) endfunction Best Case: match from the firs comparison Best Case: 1 comparison 1 7 9 12 33 42 59 76 81 84 91 92 93 99 Target: 59
  • 37. Binary Search Analysis: Worst Case Function Find return boolean (A Array, first, last, to_find) middle <- (first + last) div 2 if (first > last) then return false elseif (A[middle] = to_find) then return true elseif (to_find < A[middle]) then return Find(A, first, middle–1, to_find) else return Find(A, middle+1, last, to_find) endfunction Worst Case: divide until reach one item, or no match. 1 7 9 12 33 42 59 76 81 84 91 92 93 99 How many comparisons??
  • 38. Binary Search Analysis: Worst Case • With each comparison we throw away ½ of the list N N/2 N/4 N/8 1 ………… 1 comparison ………… 1 comparison ………… 1 comparison ………… 1 comparison ………… 1 comparison . . . Number of steps is at most Log2N
  • 39. Summary • Binary search reduces the work by half at each comparison • If array is not sorted  Linear Search – Best Case O(1) – Worst Case O(N) • If array is sorted  Binary search – Best Case O(1) – Worst Case O(Log2N)