Created
May 25, 2019 10:49
-
-
Save Kirill255/9abc03b38e70f95c85421946eb55f434 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// бинарный поиск | |
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; | |
function binary_search(num) { | |
var low = 0; | |
var high = arr.length - 1; | |
while (low <= high) { | |
var middleIndex = Math.round((low + high) / 2); | |
if (arr[middleIndex] === num) { | |
return console.log(`Num ${num} — index: ${middleIndex}`); | |
} else if (arr[middleIndex] > num) { | |
high = middleIndex - 1; | |
} else { | |
low = middleIndex + 1; | |
} | |
} | |
return console.log(`Num ${num} — none!`); | |
} | |
binary_search(20); | |
binary_search(8); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment