
In the end, if the element is present in the list, its index is returned. In this article, we will learn about the Binary search algorithm.
| Binary Search Algorithm |
| binary_Search( a, lower_bound, upper_bound, target) Step 1: set start = lower_bound, end = upper_bound, pos = - 1 Step 2: repeat steps 3 and 4 while start <=end Step 3: set mid = (start + end)/2 or start+(end-start)/2 Step 4: if a[mid] = target set pos = mid print pos go to step 6 else if a[mid] > target set end = mid - 1 else set start = mid + 1 [end of if] [end of loop] Step 5: if pos = -1 print "Not Present" [end of if] Step 6: exit |
| Time Complexity of Binary Search Algorithm | |
| Case | Time Complexity |
| Best Case | O(1) |
| Average Case | O(logN) |
| Worst Case | O(logN) |
| Space Complexity of Binary Search Algorithm |
| O(1) |
| Difference Between Linear Search and Binary Search Algorithm | |
| The Linear Search algorithm works by traversing the complete list one by one to search the target element. | The Binary Search Algorithm is an efficient algorithm for finding an item from a sorted list of items |
| It does not require the list element to be sorted. | It requires the elements to be in sorted order. |
| The time complexity of the linear search algorithm is O(N), where N is the number of elements in the array. | The time complexity of a binary search algorithm is O(logN), where N is the number of elements in the list. |
| It only works with the divide-and-conquer approach. | It works on the divide and conquer approach. |
| It is simple but inefficient for large datasets. | It is suitable for large datasets. |
| Binary Search Algorithm using C++ |
|
| Binary Search Algorithm Using Java |
class BinarySearch {
|