Output: Element is present at index 3
Time Complexity: The time complexity of Binary Search can be written as
T(n) = T(n/2) + c
The above recurrence can be solved either using the Recurrence Tree method or Master method. It falls in case II of the Master Method and the solution of the recurrence is Theta(Logn).
Auxiliary Space: O(1) in case of iterative implementation. In the case of recursive implementation, O(Logn) recursion call stack space.
Algorithmic Paradigm: Decrease and Conquer.
Note: Here we are using
int mid = low + (high – low)/2;
Maybe, you wonder why we are calculating the middle index this way, we can simply add the lower and higher index and divide it by 2.
int mid = (low + high)/2;
But if we calculate the middle index like this means our code is not 100% correct, it contains bugs.
That is, it fails for larger values of int variables low and high. Specifically, it fails if the sum of low and high is greater than the maximum positive int value(231 – 1 ).
The sum overflows to a negative value and the value stays negative when divided by 2. In java, it throws Array Index Out Of Bound Exception.
int mid = low + (high – low)/2;
So it’s better to use it like this. This bug applies equally to merge sort and other divide and conquer algorithms.
Prerequisite:
1. A linear search scans one item at a time, without jumping to any item .
2. A binary search however, cut down your search to half as soon as you find middle of a sorted list.
Important Differences
Let us look at an example to compare the two:
1. Linear Search to find the element “J” in a given sorted list from A-X
2. Binary Search to find the element “J” in a given sorted list from A-X
81 videos|80 docs|33 tests
|
|
Explore Courses for Computer Science Engineering (CSE) exam
|