Created
July 17, 2020 16:25
-
-
Save anishLearnsToCode/4b6718f28401a3f5705e6525fa4e01d9 to your computer and use it in GitHub Desktop.
This is the binary search algorithm that returns the position at which an element is found or the position it should be inserted at.
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
/* | |
This is the binary search algorithm that returns the position at which an | |
element is found or the position it should be inserted at if the element is not present. | |
In other words this algorithm returns position (non conforming in case of duplicates) or the position | |
of largest element than the one we were searching for if position not found. | |
*/ | |
class BinarySearch { | |
private static int search(int[] array, int val) { | |
int left = 0, right = array.length - 1, middle; | |
while (left <= right) { | |
middle = left + (right - left) / 2; | |
if (array[middle] == val) return middle; | |
else if (array[middle] > val) right = middle - 1; | |
else left = middle + 1; | |
} | |
return left; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment