Skip to content

Instantly share code, notes, and snippets.

@mansi7babbar
Last active July 18, 2021 07:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mansi7babbar/380f67d421bebfcd95201de181b21b4b to your computer and use it in GitHub Desktop.
Save mansi7babbar/380f67d421bebfcd95201de181b21b4b to your computer and use it in GitHub Desktop.
class BinarySearch
{
public static int binarySearchRecursive(int[] list, int first, int last, int key)
{
if(first >= last)
{
return -1;
}
int middle = first + (last - first) / 2;
if(list[middle] == key)
{
return middle;
}
else if(list[middle] < key)
{
first = middle + 1;
return binarySearchRecursive(list, first, last, key);
}
else
{
last = middle - 1;
return binarySearchRecursive(list, first, last, key);
}
}
public static void main(String[] args)
{
int[] list = {10, 14, 19, 26, 27, 31, 33, 35, 42, 44};
int element = 31;
int result = binarySearchRecursive(list, 0, list.length - 1, element);
if(result == -1)
{
System.out.println("The element does not exist in the list");
}
else
{
System.out.println("The element found at index : " + result);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment