0% found this document useful (0 votes)
4 views

Algorithm

Uploaded by

ranamehvika220
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Algorithm

Uploaded by

ranamehvika220
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

Algorithm: Binary Search

1. Define a function binary_search that takes a sorted array arr and a


target element target as input.
2. Initialize two pointers, left and right, to the start and end indices of
the array, respectively.
3. Enter a loop that continues as long as left is less than or equal to
right.
4. Calculate the middle index mid as (left + right) // 2.
5. Compare the element at index mid in the array with the target
element.
 If they are equal, return mid as the index of the target
element.
 If the element at mid is greater than the target, update right
to mid - 1 to search in the left half of the array.
 If the element at mid is less than the target, update left to
mid + 1 to search in the right half of the array.
6. If the loop exits without finding the target element, return -1 to
indicate that the target element is not in the array.

You might also like