Skip to content

Instantly share code, notes, and snippets.

@mansi7babbar
Created July 18, 2021 15:09
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/0a57810c859973e90f8fc522a67c3fdd to your computer and use it in GitHub Desktop.
Save mansi7babbar/0a57810c859973e90f8fc522a67c3fdd to your computer and use it in GitHub Desktop.
class BinarySearchAlgorithm
{
public static int recursiveBinarySearch(int[] list, int low, int high, int key)
{
if( low >= high)
{
return -1;
}
int middle = low + (high - low) / 2;
if(list[middle] == key)
{
return middle;
}
else if(list[middle] < key)
{
low = middle + 1;
return recursiveBinarySearch(list, low, high, key);
}
else
{
high = middle - 1;
return recursiveBinarySearch(list, low, high, key);
}
}
public static int iterativeBinarySearch(int[] list, int low, int high, int key)
{
while(low <= high)
{
int middle = low + (high - low) / 2;
if(list[middle] == key)
{
return middle;
}
else if(list[middle] < key)
{
low = middle + 1;
}
else
{
high = middle - 1;
}
}
return -1;
}
public static void main(String[] args)
{
int[] list = {1, 3, 4, 6, 7, 9, 10, 11, 13};
int recursiveBinarySearchResult = recursiveBinarySearch(list, 0, list.length - 1, 6);
if(recursiveBinarySearchResult == -1)
{
System.out.println("The item does not exist in the list");
}
else
{
System.out.println("The item found at index : " + result);
}
int iterativeBinarySearchResult = iterativeBinarySearch(list, 0, list.length - 1, 12);
if(iterativeBinarySearchResult == -1)
{
System.out.println("The item does not exist in the list");
}
else
{
System.out.println("The item found at index : " + result);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment