Skip to content

Commit 9a6c38e

Browse files
Merge pull request #110 from nicolefffe/js-binary-search
issue #86 - add binary search algorithm for javascript
2 parents 63d2d73 + 8869399 commit 9a6c38e

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// can execute script with Node.js (v6) by running: node BinarySearch.js
2+
3+
const generateArray = (length, multiplier) => {
4+
let arr = [];
5+
for (i = 1; i <= length; i++) {
6+
arr.push(i * multiplier);
7+
}
8+
return arr;
9+
};
10+
11+
const binarySearch = (arr, valueToFind) => {
12+
let min = 0;
13+
let max = arr.length - 1;
14+
let iterations = 0;
15+
let searchIndex, found;
16+
17+
while (max >= min) {
18+
// start by looking at value in middle of array (assuming it is sorted)
19+
searchIndex = Math.floor((max + min) / 2);
20+
foundValue = arr[searchIndex];
21+
iterations++;
22+
23+
if (foundValue === valueToFind) {
24+
break;
25+
}
26+
// on each iteration, reduce search range by half by:
27+
// adjusting min if midway value was less than search value, or
28+
// adjusting max if midway value was greater than search value
29+
min = foundValue < valueToFind ? searchIndex + 1 : min;
30+
max = foundValue > valueToFind ? searchIndex - 1 : max;
31+
}
32+
foundValue = foundValue === valueToFind ? valueToFind : -1;
33+
return {
34+
foundValue,
35+
searchIndex,
36+
iterations
37+
};
38+
};
39+
40+
const main = () => {
41+
const arr = generateArray(Math.ceil(Math.random() * 100), Math.ceil(Math.random() * 10));
42+
console.log(`Array is: [ ${arr.join(', ')} ]`);
43+
44+
const value = Math.ceil(Math.random() * 100);
45+
console.log(`Will attempt to find ${value} in array.`);
46+
47+
const { foundValue, iterations, searchIndex } = binarySearch(arr, value);
48+
if (foundValue === -1) {
49+
console.log(`Did not find value in ${iterations} iterations.`)
50+
} else {
51+
console.log(`Found ${foundValue} at index ${searchIndex} after ${iterations} iterations.`)
52+
}
53+
};
54+
55+
main();

0 commit comments

Comments
 (0)