Binary search is a searching algorithm which is used to search a number in a sorted array or list.
Description:
Binary search uses Decrease and Conquer Algorithm. In this algorithm original problem is decreased by a constant factor and a sub-problem is created and then the sub-problem is further solved to get the solution of the original problem. This process keeps on going unless the problem is solved or no further division is possible.
Procedure for Binary Search:
First sort the array (ascending or descending totally depends upon user)
Start = 0, end = length (array) – 1
Mid = (start + end) / 2
While start is less than end
If array[mid] == number
Print number found and exit
If array[mid] > number
End = mid – 1
Mid = (start + end) / 2
If array[mid] < number
Start = mid + 1
Mid = (start + end) / 2
End of while
Time Complexity : O(logn)
Note: For binary search array or list needs to be sorted before searching otherwise one may not get correct result.
Python code for binary search
Output
need an explanation for this answer? contact us directly to get an explanation for this answer