Skip to content

Instantly share code, notes, and snippets.

@IdrissDimson
Last active December 2, 2022 22:16
Show Gist options
  • Save IdrissDimson/bf6821251b51bb4572231fb787222c51 to your computer and use it in GitHub Desktop.
Save IdrissDimson/bf6821251b51bb4572231fb787222c51 to your computer and use it in GitHub Desktop.
class BinarySearch {
int doSearch(int arr[], int targetValue)
{
int min = 0;
int max = arr.length - 1;
int guess;
while (min <= max)
{
// split the array in half
guess = min + (max - min) / 2;
// if the target value is found, return the index
// of the array
if(arr[guess] == targetValue)
{
return guess;
}
// if the value is less than the target, raise
// the minimum value by one
else if(arr[guess] < targetValue)
{
min = guess + 1;
}
// if the value is greater than the target, lower
// the maximum value by one
else
{
max = guess - 1;
}
}
// if the value is not present, return -1
return -1;
}
public static void main(String[] args)
{
BinarySearch bs = new BinarySearch();
int primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,
41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
int targetValue = 97;
int result = bs.doSearch(primes, targetValue);
if (result == -1)
System.out.println("Number not present");
else
System.out.println("Number found at index "
+ result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment