Skip to content

Instantly share code, notes, and snippets.

@mansi7babbar
Last active July 18, 2021 07:41
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/3673fdaf4d1044b77d64ae04d05a3ef2 to your computer and use it in GitHub Desktop.
Save mansi7babbar/3673fdaf4d1044b77d64ae04d05a3ef2 to your computer and use it in GitHub Desktop.
class BinarySearch
{
public static int binarySearchIterative(int[] list, int first, int last, int key)
{
while(first <= last)
{
int middle = first + (last - first) / 2;
if(list[middle] == key)
{
return middle;
}
else if(list[middle] < key)
{
first = middle + 1;
}
else
{
last = middle - 1;
}
}
return -1;
}
public static void main(String[] args)
{
int[] list = {10, 14, 19, 26, 27, 31, 33, 35, 42, 44};
int element = 31;
int result = binarySearchIterative(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