Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // first = true - find first occurance
- // first = false - find last occurance
- // first = undefined - first found
- function binarySearch(array, x, first) {
- var start = 0, end = array.length - 1, mid = 0, result = -1;
- while (start <= end) {
- mid = Math.floor((start + end) / 2);
- if (array[mid] == x) {
- result = mid;
- if (typeof first === 'undefined') {
- return result;
- } else if (first === true) {
- end = mid - 1;
- } else if (first === false) {
- start = mid + 1;
- }
- } else if (x < array[mid]) {
- end = mid - 1;
- } else {
- start = mid + 1;
- }
- }
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement