forked from loiane/javascript-datastructures-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary-search.js
24 lines (23 loc) · 795 Bytes
/
binary-search.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { Compare, defaultCompare, DOES_NOT_EXIST } from '../../util';
import { quickSort } from '../sorting/quicksort';
export function binarySearch(array, value, compareFn = defaultCompare) {
const sortedArray = quickSort(array);
let low = 0;
let high = sortedArray.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
const element = sortedArray[mid];
// console.log('mid element is ' + element);
if (compareFn(element, value) === Compare.LESS_THAN) {
low = mid + 1;
// console.log('low is ' + low);
} else if (compareFn(element, value) === Compare.BIGGER_THAN) {
high = mid - 1;
// console.log('high is ' + high);
} else {
// console.log('found it');
return mid;
}
}
return DOES_NOT_EXIST;
}