Merge pull request #2 from kevinwin/ch1
code for chapter 1 in javascript
This commit is contained in:
26
01_introduction_to_algorithms/javascript/01_binary_search.js
Normal file
26
01_introduction_to_algorithms/javascript/01_binary_search.js
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
function binary_search(list, item) {
|
||||||
|
let low = 0;
|
||||||
|
let high = list.length - 1;
|
||||||
|
|
||||||
|
while (low <= high) {
|
||||||
|
let mid = Math.floor((low + high) / 2);
|
||||||
|
let guess = list[mid];
|
||||||
|
if (guess === item) {
|
||||||
|
return mid;
|
||||||
|
}
|
||||||
|
if (guess > item) {
|
||||||
|
high = mid - 1;
|
||||||
|
} else {
|
||||||
|
low = mid + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const my_list = [1, 3, 5, 7, 9];
|
||||||
|
|
||||||
|
console.log(binary_search(my_list, 3)); // 1
|
||||||
|
console.log(binary_search(my_list, -1)); // null
|
||||||
Reference in New Issue
Block a user