Binary Search is nothing but a Searching Algorithm. Which will help you search a element in array. Binary Search is most efficient algorithm for searching a element. The important thing about Binary Search is that, it will only apply to “sorted array”. The array should be sorted or else it will not work.
It is faster Algorithm because you can eliminate half of the remaining elements at a time. For eg:
In a given array {1,4,5,10,15,22,55,94} You want to find value 10. The algorithm approach will be, First it will find mid value,start and end value of a array. which is 15,1,94 respectively in this case and now it will check if find value is greater or lesser than “mid value” Is 10 is greater or lesser than mid value? if yes we don’t care about rest of the elements. Now we only care about{1,4,5,10,15} Now again we will repeat the process again now the start element will be index 0 which is 1 and end element will be index 4 which is 15 and mid value(To cal mid value (start+end) / 2)) will be 5. Now you again check if 5 is greater or lesser than “find value” if it is greater than Repeat the process again. Now we care about {5,10,15}. Now again we repeat the process till we match will “find value” In the end We got the value 10. basically we use Divide and Conquer.
The Pseudo-Code will be:
- Create a method/function that takes sorted array.
- Create a var start,mid and end of the array.
- Now Create a While loop and check whether the “find value” is lesser or greater than mid value. And you will write code in such a way that the start should come before end. And update a the mid value very loop until it find the “Find value”.
- If the value is to small, move the start up.
- If the value is to big, move the end down.
Code In Java
public class Main {
public static void main(String[] args) {
int[] arr ={1,2,5,10,17,28,30,52};
int find = 52;
int start= 0;
int end = arr.length-1;
int mid = (start+end) / 2;
// System.out.println(mid);
while (arr[mid] != find && start <= end){
System.out.println(mid);
if (find < arr[mid]){
end = mid - 1;
}else {
start = mid + 1;
}
mid = (start+end) / 2;
}
if (arr[mid] == find){
System.out.println(mid);
}else {
System.out.println(-1);
}
}
}