Created
April 1, 2023 23:15
-
-
Save jainal09/aa1885279a1ed952542f10822ec7ca54 to your computer and use it in GitHub Desktop.
Binary Search in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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