# binary search in java

223 views
Binary search in java.How does binary search work in java?

by (2.8k points)

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

by (2.8k points)

Binary Search:- If you want to search any element in your given array, them array must be sorted order.

See the bellow code to search element in given array by binary search using recursion:-

//User recursive solution

//Time Complexity O(logN)

private static boolean search(int[] arr, int l, int h, int x) {

//Corner cases; Whe;resent

if(l>h) {

return false;

}

int mid = (l+h)/2; // mid = l + (h-l)/2;

if(arr[mid] == x) {

return true;

}else if(x > arr[mid]) {

return search(arr, mid+1, h, x);

}else if(x < arr[mid]) {

return search(arr, l, mid-1, x);

}

return false;

}