Last active
August 11, 2019 14:06
-
-
Save wszdwp/8bfd51faea88633fb59c4b78a3742441 to your computer and use it in GitHub Desktop.
binary search ref: https://zxi.mytechroad.com/blog/algorithms/binary-search/sp5-binary-search/
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
public int binarySearch(int[] arr, int target) { | |
int l = 0, r = arr.length; | |
while (l < r) { | |
int m = l + (r - l) / 2; | |
if (arr[m] == target) return m; | |
else if (arr[m] > target) { | |
r = m; | |
} | |
else { | |
l = m + 1; | |
} | |
} | |
return l; | |
} | |
// find(target): arr[i] = target | |
// lowerBound(target): 1st index i makes arr[i] >= target | |
// upperBound(target): 1st index i makes arr[i] > target | |
public int binarySearchLowerBound(int[] arr, int target) { | |
int l = 0, r = arr.length; | |
while (l < r) { | |
int m = l + (r - l) / 2; | |
else if (arr[m] >= target) { | |
r = m; | |
} | |
else { | |
l = m + 1; | |
} | |
} | |
return l; | |
} | |
public int binarySearchUpperBound(int[] arr, int target) { | |
int l = 0, r = arr.length; | |
while (l < r) { | |
int m = l + (r - l) / 2; | |
else if (arr[m] > target) { | |
r = m; | |
} | |
else { | |
l = m + 1; | |
} | |
} | |
return l; | |
} | |
// Ref | |
[https://zxi.mytechroad.com/blog/algorithms/binary-search/sp5-binary-search/](https://zxi.mytechroad.com/blog/algorithms/binary-search/sp5-binary-search/) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment