Skip to content

Commit 0a19df0

Browse files
authored
Merge pull request egonSchiele#2 from kevinwin/ch1
code for chapter 1 in javascript
2 parents 848994f + 1b3370e commit 0a19df0

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
'use strict';
2+
3+
function binary_search(list, item) {
4+
let low = 0;
5+
let high = list.length - 1;
6+
7+
while (low <= high) {
8+
let mid = Math.floor((low + high) / 2);
9+
let guess = list[mid];
10+
  if (guess === item) {
11+
return mid;
12+
}
13+
if (guess > item) {
14+
high = mid - 1;
15+
} else {
16+
low = mid + 1;
17+
}
18+
}
19+
20+
return null;
21+
}
22+
23+
const my_list = [1, 3, 5, 7, 9];
24+
25+
console.log(binary_search(my_list, 3)); // 1
26+
console.log(binary_search(my_list, -1)); // null

0 commit comments

Comments
 (0)