Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

15. Data Structure and Algorithms Binary Search

Binary search is an efficient algorithm with a time complexity of O(log n) that operates on sorted data collections. It works by comparing the target item with the middle element and recursively searching in the appropriate sub-array based on the comparison. The process continues until the item is found or the sub-array size reduces to zero.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

15. Data Structure and Algorithms Binary Search

Binary search is an efficient algorithm with a time complexity of O(log n) that operates on sorted data collections. It works by comparing the target item with the middle element and recursively searching in the appropriate sub-array based on the comparison. The process continues until the item is found or the sub-array size reduces to zero.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Data Structure and

Algorithms Binary
Search
 Binary search is a fast search algorithm with run-time complexity of Ο(log n).
This search algorithm works on the principle of divide and conquer. For this
algorithm to work properly, the data collection should be in the sorted form.
 Binary search looks for a particular item by comparing the middle most item
of the collection. If a match occurs, then the index of item is returned. If the
middle item is greater than the item, then the item is searched in the sub-
array to the left of the middle item. Otherwise, the item is searched for in the
sub-array to the right of the middle item. This process continues on the sub-
array as well until the size of the subarray reduces to zero.

In a nutshell, this search algorithm takes advantage of a collection of elements


that is already sorted by ignoring half of the elements after just one
comparison.
 Compare x with the middle element.
 If x matches with the middle element, we return the mid index.
 Else if x is greater than the mid element, then x can only lie in the right
(greater) half subarray after the mid element. Then we apply the algorithm
again for the right half.
 Else if x is smaller, the target x must lie in the left (lower) half. So we apply
the algorithm for the left half.
Python Program for Binary Search (Recursive and Iterative)
Output:
Element is present at index 3

You might also like