Binary Search:- Binary search is used to search a key element from multiple elements. As we know that, binary search is faster than linear search or sequential search. If you want to search any element in given array then array must be a sorted way. If your array is not sorted then first of all sort an array by using Arrays.sort(arr) method.
See the following running java code of binary search:-
//Iterative solution
//Time Complexity O(logN)
private static boolean search(int[] arr, int l, int h, int x) {
while(l<=h) {
int mid = l+(h-l)/2;
if(arr[mid] == x) {
return true;
}else if(x > arr[mid]) {
l = mid+1;
}else if(x < arr[mid]) {
h = mid-1;
}
}
return false;
}
private static boolean doBinarySearch(int[] arr, int x) {
return search(arr, 0, arr.length-1, x);
}
public static void main(String[] args) {
int arr[] = {5,20,40,60,100};
int search = 100;
boolean isFound = doBinarySearch(arr, search);
System.out.println("Search: " + isFound);
}
Output:-
Search: true