Binary Search Algorithm | Beginner’s Algorithm
Binary search mainly used in searching element from sorted array, we divide the array into two half to reduce the time complexities, we repeat this this untill we get the required element.
Prerequisite – The array must be sorted.
Time Complexity – O (logN)
Space Complexity – O(1)
Algorithm with Sepearate Method
public class Main { public static void main(String[] args) { int arr[]={1,2,3,4,5,6,7}; System.out.println(binarySearch(arr,2)); } public static int binarySearch(int arr[],int ele){ int n=arr.length; int low=0; int high=n-1; while(low<=high){ int mid=(low+high)/2; if(arr[mid]<ele){ low=mid+1; }else if(arr[mid]>ele){ high=mid-1; }else if(arr[mid]==ele){ return mid; } } return -1; } }
Algorithm inside Main Method
public class Main { public static void main(String[] args) { int arr[]={1,2,3,4,5,6,7}; int n=arr.length; int ele=10; int low=0; int high=n-1; int ans=-1; while(low<=high){ int mid=(low+high)/2; if(arr[mid]<ele){ low=mid+1; }else if(arr[mid]>ele){ high=mid-1; }else if(arr[mid]==ele){ ans=mid; break; } } System.out.println(ans); } }