Binary Search
-
Binary Search is a searching algorithm to find an element from a Sorted Array. This type of search is also known as half-interval search or logarithmic search. Binary Search like Linear Search applies to Linear Data Structures like Arrays and Hash Tables. Binary Search is one of the best performing search algorithm for Linear Data Structures and has many practical use cases.
Time complexity of Binary Search is O(log n) and space complexity is O(1). This is a logarithmic search algorithm and Time complexity line is always well below the Linear Time Complexity line. That means, Binary Search performance increases as the number of inputs increases, making this suitable for larger data collections.
Binary Search Uses
Binary search can be used to find solutions for a wider range of problems. Some of the use cases are listed below.
- Used mainly for use cases that manages huge amount of data and faster search is of the primary importance above insert update and delete operations, like in a dictionary.
- Finding the next-smallest or next-largest element in the array relative to a target element.
- Numerical solutions to an equation.
- Can be used to access ordered data quickly when memory space is tight.
-
How Binary Search Works
Binary Search is a divide and conquer method, that has higher efficiency for larger sets of data. Binary Search should be performed on a sorted array, whereas in Linear Search, array can be in any order.
This algorithm basically compares the search element with the middle element of the remaining array. Then checks if it is greater or lesser or equal and eliminating the other half for each iteration, till the result is obtained. Binary search is a well performing algorithm and has many practical applications.
Check the below gif image to easily understand the search process.
As you can see, Binary Search require the data to be kept sorted and this may be an additional overhead for insert, update or delete operations.
-
Algorithm
Binary Search Algorithm flow is listed as below.
Input : A sorted list of elements.
Output : Element position, if found. Else not found message.- Start.
- Set start = 0, end = length of array, pos = -1.
- Check start <= end, if true go to next step, else go to step 8.
- Find middle node.
- If middle node value = searched value, element found. Go to step 8.
- Else if middle node value < searched value, set start = middle node + 1. Go to step 4.
- Else, end = middle node - 1. Go to step 4.
- If pos > -1, element found. Display result.
- Else if pos = -1, element not found. Display not found message.
- Stop.
-
Code Samples
Below are few sample code implementations of Binary Search Algorithm in Python, Java, C# and JavaScript.