Skip to content

Instantly share code, notes, and snippets.

@jainal09
Created April 1, 2023 23:15
Show Gist options
  • Save jainal09/aa1885279a1ed952542f10822ec7ca54 to your computer and use it in GitHub Desktop.
Save jainal09/aa1885279a1ed952542f10822ec7ca54 to your computer and use it in GitHub Desktop.
Binary Search in Java
/*
* A binary search algorithm implementation in Java
*/
public class MyBinarySearch {
public static void main(String[] args) {
int[] numbers = {2, 12, 15, 17, 27, 29, 45};
int targetValue = 17;
System.out.println(binarySearch(numbers, targetValue));
}
static int binarySearch(int[] numbers, int targetValue) {
int startIndex = 0;
int endIndex = numbers.length - 1;
while (startIndex <= endIndex) {
int middleIndex = startIndex + (endIndex - startIndex) / 2;
if (numbers[middleIndex] > targetValue)
endIndex = middleIndex - 1;
else if (numbers[middleIndex] < targetValue)
startIndex = middleIndex + 1;
else
return middleIndex;
}
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment