SlideShare a Scribd company logo
1 of 28
Download to read offline
1
© 2006 Pearson Addison-Wesley. All rights reserved
Searching and Sorting
• Linear Search
• Binary Search
2
© 2006 Pearson Addison-Wesley. All rights reserved
Linear Search
• Searching is the process of determining whether or not a
given value exists in a data structure or a storage media.
• We discuss two searching methods on one-dimensional
arrays: linear search and binary search.
• The linear (or sequential) search algorithm on an array is:
– Sequentially scan the array, comparing each array item with the searched value.
– If a match is found; return the index of the matched element; otherwise return –1.
• Note: linear search can be applied to both sorted and unsorted
arrays.
3
© 2006 Pearson Addison-Wesley. All rights reserved
Linear Search
4
© 2006 Pearson Addison-Wesley. All rights reserved
Linear Search
Algorithm
• Assume we need to find an element that is in an array in random order.
• Start with the first position and compare it to the target in order to search for a
target element.
• If the current element matches the target element, return the position of the
current element.
• If not, move on to the next one until we reach the very end of an array.
• If still unable to find the target, return -1.
5
© 2006 Pearson Addison-Wesley. All rights reserved
Linear Search
6
© 2006 Pearson Addison-Wesley. All rights reserved
Linear Search
7
© 2006 Pearson Addison-Wesley. All rights reserved
Binary Search
• Binary search uses a recursive method to search
an array to find a specified value
• The array must be a sorted array:
a[0]≤a[1]≤a[2]≤. . . ≤ a[finalIndex]
• If the value is found, its index is returned
• If the value is not found, -1 is returned
• Note: Each execution of the recursive method
reduces the search space by about a half
8
© 2006 Pearson Addison-Wesley. All rights reserved
Binary Search
• An algorithm to solve this task looks at the
middle of the array or array segment first
• If the value looked for is smaller than the value
in the middle of the array
– Then the second half of the array or array segment
can be ignored
– This strategy is then applied to the first half of the
array or array segment
9
© 2006 Pearson Addison-Wesley. All rights reserved
Binary Search
• If the value looked for is larger than the value in the
middle of the array or array segment
– Then the first half of the array or array segment can be ignored
– This strategy is then applied to the second half of the array or
array segment
• If the value looked for is at the middle of the array or
array segment, then it has been found
• If the entire array (or array segment) has been searched
in this way without finding the value, then it is not in the
array
10
© 2006 Pearson Addison-Wesley. All rights reserved
Pseudocode for Binary Search
11
© 2006 Pearson Addison-Wesley. All rights reserved
Recursive Method for Binary Search
12
© 2006 Pearson Addison-Wesley. All rights reserved
Execution of the Method search
(Part 1 of 2)
13
© 2006 Pearson Addison-Wesley. All rights reserved
Execution of the Method search
(Part 1 of 2)
14
© 2006 Pearson Addison-Wesley. All rights reserved
Execution of the Method search
15
© 2006 Pearson Addison-Wesley. All rights reserved
Checking the search Method
• Algorithm
1. Start with the middle element of the array as a current key.
2. If the middle element value matches the target element then return
the index of the middle element.
3. Else check if the target element is lesser than the middle element,
then continue the search in the left half.
4. If the target element is greater than the middle element, then
continue the search in the right half.
5. Check from the second point repeatedly until the value is found or
the array is empty.
6. If still unable to find the target, return -1.
16
© 2006 Pearson Addison-Wesley. All rights reserved
17
© 2006 Pearson Addison-Wesley. All rights reserved
Checking the search Method
1. There is no infinite recursion
• On each recursive call, the value of first
is increased, or the value of last is
decreased
• If the chain of recursive calls does not end
in some other way, then eventually the
method will be called with first larger
than last
18
© 2006 Pearson Addison-Wesley. All rights reserved
Checking the search Method
2. Each stopping case performs the correct
action for that case
• If first > last, there are no array
elements between a[first] and
a[last], so key is not in this segment of
the array, and result is correctly set to -
1
• If key == a[mid], result is correctly
set to mid
19
© 2006 Pearson Addison-Wesley. All rights reserved
Checking the search Method
3. For each of the cases that involve recursion, if
all recursive calls perform their actions
correctly, then the entire case performs
correctly
• If key < a[mid], then key must be one of the
elements a[first] through a[mid-1], or it is
not in the array
• The method should then search only those
elements, which it does
• The recursive call is correct, therefore the entire
action is correct
20
© 2006 Pearson Addison-Wesley. All rights reserved
Checking the search Method
• If key > a[mid], then key must be one of the
elements a[mid+1] through a[last], or it is
not in the array
• The method should then search only those
elements, which it does
• The recursive call is correct, therefore the entire
action is correct
The method search passes all three tests:
Therefore, it is a good recursive method definition
21
© 2006 Pearson Addison-Wesley. All rights reserved
Efficiency of Binary Search
• The binary search algorithm is extremely
fast compared to an algorithm that tries all
array elements in order
– About half the array is eliminated from
consideration right at the start
– Then a quarter of the array, then an eighth of
the array, and so forth
22
© 2006 Pearson Addison-Wesley. All rights reserved
Efficiency of Binary Search
• Given an array with 1,000 elements, the binary search
will only need to compare about 10 array elements to the
key value, as compared to an average of 500 for a serial
search algorithm
• The binary search algorithm has a worst-case running
time that is logarithmic: O(log n)
– A serial search algorithm is linear: O(n)
• If desired, the recursive version of the method search
can be converted to an iterative version that will run
more efficiently
23
© 2006 Pearson Addison-Wesley. All rights reserved
Iterative Version of Binary Search
(Part 1 of 2)
24
© 2006 Pearson Addison-Wesley. All rights reserved
Iterative Version of Binary Search
(Part 2 of 2)
25
© 2006 Pearson Addison-Wesley. All rights reserved
26
© 2006 Pearson Addison-Wesley. All rights reserved
27
© 2006 Pearson Addison-Wesley. All rights reserved
Linear Search and Binary Search Time Complexity Analysis
Linear Search
The Best Case:
When the array's first element is the target element. In this case, there is only
one comparison. Hence, the time complexity becomes O(1).
The Average Case:
Somewhere in the middle of the array will be the target element. In this case, N/2
will be the number of comparisons. Hence, the time complexity becomes O(N).
The Worst Case:
When the array's last element is the target element. In this case, the whole array
is traversed. Hence, the time complexity becomes O(N).
Binary Search
The Best Case:
When the array's middle element is the target element. In this case, there is only
one comparison. Hence, the time complexity becomes O(1).
The Average Case:
Anywhere in the array will be the target element. In this case, the time complexity
becomes O(logN).
The Worst Case:
When the array does not have the target element or is far away from the middle
element. In this case, the time complexity becomes O(logN).
Conclusion
➢ As a developer, you should be aware of the basic computer science concept of
search algorithms such as linear search and binary search.
➢ In a linear search, each element in the list is searched one after the other in a
sequential manner until it is found in the list.
➢ A binary search, on the other hand, finds the list’s middle element recursively until
the middle element matches a searched element.
➢ Linear search can be suitable for searching over an unsorted array. whereas,
Elements in the array need to be in sorted order for binary search.
➢ The binary search algorithm uses the divide-and-conquer approach, it does not
scan every element in the list. Hence, It is the best search algorithm.
➢ The average case time complexity of linear search and binary search is O(N) and
O(logN), respectively.
28
© 2006 Pearson Addison-Wesley. All rights reserved

More Related Content

Similar to Searching Algorithms for students of CS and IT using C++

Data Structures_ Sorting & Searching
Data Structures_ Sorting & SearchingData Structures_ Sorting & Searching
Data Structures_ Sorting & SearchingThenmozhiK5
 
Binary search algorithm.pptx
Binary search  algorithm.pptxBinary search  algorithm.pptx
Binary search algorithm.pptxbhuvansaachi18
 
Data structure and algorithms
Data structure and algorithmsData structure and algorithms
Data structure and algorithmstechnologygyan
 
Searching techniques in Data Structure And Algorithm
Searching techniques in Data Structure And AlgorithmSearching techniques in Data Structure And Algorithm
Searching techniques in Data Structure And Algorithm03446940736
 
Algorithm & data structures lec4&5
Algorithm & data structures lec4&5Algorithm & data structures lec4&5
Algorithm & data structures lec4&5Abdul Khan
 
SORTING techniques.pptx
SORTING techniques.pptxSORTING techniques.pptx
SORTING techniques.pptxDr.Shweta
 
programming in C
programming in Cprogramming in C
programming in CADITHYAM19
 
Dsa – data structure and algorithms searching
Dsa – data structure and algorithms   searchingDsa – data structure and algorithms   searching
Dsa – data structure and algorithms searchingsajinis3
 
Binary search Algorithm
Binary search AlgorithmBinary search Algorithm
Binary search AlgorithmFazalRehman79
 
Searching in Data Structure(Linear search and Binary search)
Searching in Data Structure(Linear search and Binary search)Searching in Data Structure(Linear search and Binary search)
Searching in Data Structure(Linear search and Binary search)SURBHI SAROHA
 
advanced searching and sorting.pdf
advanced searching and sorting.pdfadvanced searching and sorting.pdf
advanced searching and sorting.pdfharamaya university
 
BCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHI
BCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHIBCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHI
BCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHISowmya Jyothi
 
Searching & Sorting Algorithms
Searching & Sorting AlgorithmsSearching & Sorting Algorithms
Searching & Sorting AlgorithmsRahul Jamwal
 
IRJET- A Survey on Different Searching Algorithms
IRJET- A Survey on Different Searching AlgorithmsIRJET- A Survey on Different Searching Algorithms
IRJET- A Survey on Different Searching AlgorithmsIRJET Journal
 
searching techniques.pptx
searching techniques.pptxsearching techniques.pptx
searching techniques.pptxDr.Shweta
 

Similar to Searching Algorithms for students of CS and IT using C++ (20)

Data Structures_ Sorting & Searching
Data Structures_ Sorting & SearchingData Structures_ Sorting & Searching
Data Structures_ Sorting & Searching
 
Binary search algorithm.pptx
Binary search  algorithm.pptxBinary search  algorithm.pptx
Binary search algorithm.pptx
 
Data structure and algorithms
Data structure and algorithmsData structure and algorithms
Data structure and algorithms
 
Searching techniques in Data Structure And Algorithm
Searching techniques in Data Structure And AlgorithmSearching techniques in Data Structure And Algorithm
Searching techniques in Data Structure And Algorithm
 
Presentation
PresentationPresentation
Presentation
 
Algorithm & data structures lec4&5
Algorithm & data structures lec4&5Algorithm & data structures lec4&5
Algorithm & data structures lec4&5
 
SORTING techniques.pptx
SORTING techniques.pptxSORTING techniques.pptx
SORTING techniques.pptx
 
Searching
SearchingSearching
Searching
 
programming in C
programming in Cprogramming in C
programming in C
 
Dsa – data structure and algorithms searching
Dsa – data structure and algorithms   searchingDsa – data structure and algorithms   searching
Dsa – data structure and algorithms searching
 
Binary search Algorithm
Binary search AlgorithmBinary search Algorithm
Binary search Algorithm
 
Searching in Data Structure(Linear search and Binary search)
Searching in Data Structure(Linear search and Binary search)Searching in Data Structure(Linear search and Binary search)
Searching in Data Structure(Linear search and Binary search)
 
Binary Search
Binary SearchBinary Search
Binary Search
 
advanced searching and sorting.pdf
advanced searching and sorting.pdfadvanced searching and sorting.pdf
advanced searching and sorting.pdf
 
BCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHI
BCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHIBCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHI
BCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHI
 
Binary.pptx
Binary.pptxBinary.pptx
Binary.pptx
 
Searching & Sorting Algorithms
Searching & Sorting AlgorithmsSearching & Sorting Algorithms
Searching & Sorting Algorithms
 
Searching techniques
Searching techniquesSearching techniques
Searching techniques
 
IRJET- A Survey on Different Searching Algorithms
IRJET- A Survey on Different Searching AlgorithmsIRJET- A Survey on Different Searching Algorithms
IRJET- A Survey on Different Searching Algorithms
 
searching techniques.pptx
searching techniques.pptxsearching techniques.pptx
searching techniques.pptx
 

Recently uploaded

Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 

Recently uploaded (20)

Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 

Searching Algorithms for students of CS and IT using C++

  • 1. 1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting • Linear Search • Binary Search
  • 2. 2 © 2006 Pearson Addison-Wesley. All rights reserved Linear Search • Searching is the process of determining whether or not a given value exists in a data structure or a storage media. • We discuss two searching methods on one-dimensional arrays: linear search and binary search. • The linear (or sequential) search algorithm on an array is: – Sequentially scan the array, comparing each array item with the searched value. – If a match is found; return the index of the matched element; otherwise return –1. • Note: linear search can be applied to both sorted and unsorted arrays.
  • 3. 3 © 2006 Pearson Addison-Wesley. All rights reserved Linear Search
  • 4. 4 © 2006 Pearson Addison-Wesley. All rights reserved Linear Search Algorithm • Assume we need to find an element that is in an array in random order. • Start with the first position and compare it to the target in order to search for a target element. • If the current element matches the target element, return the position of the current element. • If not, move on to the next one until we reach the very end of an array. • If still unable to find the target, return -1.
  • 5. 5 © 2006 Pearson Addison-Wesley. All rights reserved Linear Search
  • 6. 6 © 2006 Pearson Addison-Wesley. All rights reserved Linear Search
  • 7. 7 © 2006 Pearson Addison-Wesley. All rights reserved Binary Search • Binary search uses a recursive method to search an array to find a specified value • The array must be a sorted array: a[0]≤a[1]≤a[2]≤. . . ≤ a[finalIndex] • If the value is found, its index is returned • If the value is not found, -1 is returned • Note: Each execution of the recursive method reduces the search space by about a half
  • 8. 8 © 2006 Pearson Addison-Wesley. All rights reserved Binary Search • An algorithm to solve this task looks at the middle of the array or array segment first • If the value looked for is smaller than the value in the middle of the array – Then the second half of the array or array segment can be ignored – This strategy is then applied to the first half of the array or array segment
  • 9. 9 © 2006 Pearson Addison-Wesley. All rights reserved Binary Search • If the value looked for is larger than the value in the middle of the array or array segment – Then the first half of the array or array segment can be ignored – This strategy is then applied to the second half of the array or array segment • If the value looked for is at the middle of the array or array segment, then it has been found • If the entire array (or array segment) has been searched in this way without finding the value, then it is not in the array
  • 10. 10 © 2006 Pearson Addison-Wesley. All rights reserved Pseudocode for Binary Search
  • 11. 11 © 2006 Pearson Addison-Wesley. All rights reserved Recursive Method for Binary Search
  • 12. 12 © 2006 Pearson Addison-Wesley. All rights reserved Execution of the Method search (Part 1 of 2)
  • 13. 13 © 2006 Pearson Addison-Wesley. All rights reserved Execution of the Method search (Part 1 of 2)
  • 14. 14 © 2006 Pearson Addison-Wesley. All rights reserved Execution of the Method search
  • 15. 15 © 2006 Pearson Addison-Wesley. All rights reserved Checking the search Method • Algorithm 1. Start with the middle element of the array as a current key. 2. If the middle element value matches the target element then return the index of the middle element. 3. Else check if the target element is lesser than the middle element, then continue the search in the left half. 4. If the target element is greater than the middle element, then continue the search in the right half. 5. Check from the second point repeatedly until the value is found or the array is empty. 6. If still unable to find the target, return -1.
  • 16. 16 © 2006 Pearson Addison-Wesley. All rights reserved
  • 17. 17 © 2006 Pearson Addison-Wesley. All rights reserved Checking the search Method 1. There is no infinite recursion • On each recursive call, the value of first is increased, or the value of last is decreased • If the chain of recursive calls does not end in some other way, then eventually the method will be called with first larger than last
  • 18. 18 © 2006 Pearson Addison-Wesley. All rights reserved Checking the search Method 2. Each stopping case performs the correct action for that case • If first > last, there are no array elements between a[first] and a[last], so key is not in this segment of the array, and result is correctly set to - 1 • If key == a[mid], result is correctly set to mid
  • 19. 19 © 2006 Pearson Addison-Wesley. All rights reserved Checking the search Method 3. For each of the cases that involve recursion, if all recursive calls perform their actions correctly, then the entire case performs correctly • If key < a[mid], then key must be one of the elements a[first] through a[mid-1], or it is not in the array • The method should then search only those elements, which it does • The recursive call is correct, therefore the entire action is correct
  • 20. 20 © 2006 Pearson Addison-Wesley. All rights reserved Checking the search Method • If key > a[mid], then key must be one of the elements a[mid+1] through a[last], or it is not in the array • The method should then search only those elements, which it does • The recursive call is correct, therefore the entire action is correct The method search passes all three tests: Therefore, it is a good recursive method definition
  • 21. 21 © 2006 Pearson Addison-Wesley. All rights reserved Efficiency of Binary Search • The binary search algorithm is extremely fast compared to an algorithm that tries all array elements in order – About half the array is eliminated from consideration right at the start – Then a quarter of the array, then an eighth of the array, and so forth
  • 22. 22 © 2006 Pearson Addison-Wesley. All rights reserved Efficiency of Binary Search • Given an array with 1,000 elements, the binary search will only need to compare about 10 array elements to the key value, as compared to an average of 500 for a serial search algorithm • The binary search algorithm has a worst-case running time that is logarithmic: O(log n) – A serial search algorithm is linear: O(n) • If desired, the recursive version of the method search can be converted to an iterative version that will run more efficiently
  • 23. 23 © 2006 Pearson Addison-Wesley. All rights reserved Iterative Version of Binary Search (Part 1 of 2)
  • 24. 24 © 2006 Pearson Addison-Wesley. All rights reserved Iterative Version of Binary Search (Part 2 of 2)
  • 25. 25 © 2006 Pearson Addison-Wesley. All rights reserved
  • 26. 26 © 2006 Pearson Addison-Wesley. All rights reserved
  • 27. 27 © 2006 Pearson Addison-Wesley. All rights reserved Linear Search and Binary Search Time Complexity Analysis Linear Search The Best Case: When the array's first element is the target element. In this case, there is only one comparison. Hence, the time complexity becomes O(1). The Average Case: Somewhere in the middle of the array will be the target element. In this case, N/2 will be the number of comparisons. Hence, the time complexity becomes O(N). The Worst Case: When the array's last element is the target element. In this case, the whole array is traversed. Hence, the time complexity becomes O(N). Binary Search The Best Case: When the array's middle element is the target element. In this case, there is only one comparison. Hence, the time complexity becomes O(1). The Average Case: Anywhere in the array will be the target element. In this case, the time complexity becomes O(logN). The Worst Case: When the array does not have the target element or is far away from the middle element. In this case, the time complexity becomes O(logN).
  • 28. Conclusion ➢ As a developer, you should be aware of the basic computer science concept of search algorithms such as linear search and binary search. ➢ In a linear search, each element in the list is searched one after the other in a sequential manner until it is found in the list. ➢ A binary search, on the other hand, finds the list’s middle element recursively until the middle element matches a searched element. ➢ Linear search can be suitable for searching over an unsorted array. whereas, Elements in the array need to be in sorted order for binary search. ➢ The binary search algorithm uses the divide-and-conquer approach, it does not scan every element in the list. Hence, It is the best search algorithm. ➢ The average case time complexity of linear search and binary search is O(N) and O(logN), respectively. 28 © 2006 Pearson Addison-Wesley. All rights reserved