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

Binary Search Algorithm

The binary search algorithm requires that an array first be sorted. It then compares the target element to the middle element of the array, adjusting the search space to either the left or right half and repeating until the target is found or determined not present. The basic steps involve setting low and high indices, calculating the middle index, comparing the target to that middle element, and updating the search space accordingly.

Uploaded by

Hamza Sajid
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
161 views

Binary Search Algorithm

The binary search algorithm requires that an array first be sorted. It then compares the target element to the middle element of the array, adjusting the search space to either the left or right half and repeating until the target is found or determined not present. The basic steps involve setting low and high indices, calculating the middle index, comparing the target to that middle element, and updating the search space accordingly.

Uploaded by

Hamza Sajid
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Binary Search Algorithm

The basic steps to perform Binary Search are:


1. Sort the array in ascending order.
2. Set the low index to the first element of the array and the high index to the last
element.
3. Set the middle index to the average of the low and high indices.
4. If the element at the middle index is the target element, return the middle
index.
5. If the target element is less than the element at the middle index, set the high
index to the middle index – 1.
6. If the target element is greater than the element at the middle index, set the
low index to the middle index + 1.
7. Repeat steps 3-6 until the element is found or it is clear that the element is not
present in the array.

binarySearch(arr, x, low, high)

repeat till low = high

mid = (low + high)/2

if (x == arr[mid])
return mid

else if (x > arr[mid]) // x is on the right side


low = mid + 1

else // x is on the left side


high = mid - 1

You might also like