Binary Search Algorithm using java
Searching Algorithm :-
When you have to check or retrieve an element from the given data structure then we use searching algorithm.
It is two types :-
- Sequential Search :- Here the list or array is traversed sequentially and every element is checked.
- Interval Search :- Specifically designed for searching in sorted data-structures and are much more efficient than Sequential Search as they repeatedly target the center of the search structure and divide the search space in half.
Binary Search :-
It is a type of an efficient searching algorithm which is used for finding an element from a sorted array or list.
This sorted array can either be in ascending order or in descending order.
The idea behind binary search is that repeatedly dividing the array into halves until you’ve narrowed down the possible locations to just one.
Algorithm :-
- Take four variables = start, end, middle, target.
- Find the middle element of an array , Now your array is divided into two parts left and right.
- If [ target element > middle element ] search in right part.
- If [ target element < middle element ] search in left part.
- If [ middle element == target element ] return that element.
- If [ start > end ] element not found.
Time Complexity :-
- In each iteration or in each recursive call, the search gets reduced to half of the array.
- So for n elements in the array, there are log2n iterations or recursive calls.
Therefore, the Best Case, it means, if we get the element in 1st iteration only (middle element) = O(1) and for the Average Case and Worst Case = O(log2N).
Space Complexity is O(1).
Code Implementation :-
Explanation :-
- Created one function named BinarySearch having the parameters of an array variable and the target element variable.
- Initialize the start variable with value 0 and end variable with the value of arr.length -1 which means the last element of the array. Hence, here I am taking the starting and ending value of the sorted array.
- Start a while loop with the condition that start value should always be less than or equal to the end value.
- Then find the middle element with the given formula.
- Now check the Binary Search cases which was also explained in the algorithm of it and if none of the value matches then simply return -1.
- In the Driver Code, I have taken one sorted array and defined the target element whose index value needs to be find out and then calls the function.
This information is used to narrow the search. If you like this post, please leave a clap. Thank You !