mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-11-10 11:09:43 +08:00
Merge 7813d5ec62
into ca3d16dcce
This commit is contained in:
commit
71e4ab46d5
27
src/algorithms/search/binary-search/BinarySearch.js
Normal file
27
src/algorithms/search/binary-search/BinarySearch.js
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
var myList = [1, 3, 5, 7, 9];
|
||||||
|
|
||||||
|
function binarySearch(myList, itemToFind) {
|
||||||
|
var low = 0,
|
||||||
|
high = myList.length - 1,
|
||||||
|
mid,
|
||||||
|
guessed;
|
||||||
|
|
||||||
|
while(low <= high) {
|
||||||
|
mid = Math.floor((low + high) / 2),
|
||||||
|
guessed = myList[mid];
|
||||||
|
|
||||||
|
if(guessed === itemToFind) {
|
||||||
|
console.log('Found item at index: ' + mid + ', value is ' + guessed);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if(itemToFind < guessed) {
|
||||||
|
high = mid - 1;
|
||||||
|
} else {
|
||||||
|
low = mid + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
binarySearch(myList, 3);
|
Loading…
Reference in New Issue
Block a user