A Java Programming learning website packed with information and programs ranging from basics
, arrays
, string programs
to 2D arrays
, recursion
, matrices
and many more.
class BinarySearch {
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
return binarySearch(arr, mid + 1, r, x);
}
return -1;
}
public static void main(String args[])
{
BinarySearch ob = new BinarySearch();
int arr[] = { 2, 3, 4, 10, 40 };
int n = arr.length;
int x = 10;
int result = ob.binarySearch(arr, 0, n - 1, x);
if (result == -1)
System.out.println("Element not present");
else
System.out.println("Element found at index " + result);
}
}
Element to Search : 3
Element found at index : 1
Our docs are designed to make learning Java easy and fun.
Our maintainers devote their time, effort, and heart to ensure Javaistic keeps getting better. Support us by donating to our collective 🙏
Sponsor the Javaistic maintainers
Sponsor the Javaistic maintainers on GitHub