Last active
June 18, 2021 08:22
-
-
Save MiCkEyZzZ/57e619f3f8fab690147fe4b9116be9d8 to your computer and use it in GitHub Desktop.
Binary search implementation.txt
This file contains 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
Итеративный подход | |
function binarySearch (array, element) { | |
let start = 0 | |
let end = array.length | |
let middle | |
let found = false | |
let position = -1 | |
while (found === false && start <= end) { | |
middle = Math.floor((start + end) / 2) | |
if (array[middle] === element) { | |
found = true | |
position = middle | |
return position | |
} | |
if(element < array[middle]) { | |
end = middle - 1 | |
} else { | |
start = middle + 1 | |
} | |
} | |
} | |
Рекурсивный подход | |
function recursiveBinarySearch (array, element, start, end) { | |
let middle = Math.floor((start + end) / 2) | |
if (element === array[middle]) { | |
return middle | |
} | |
if (element < array[middle]) { | |
return recursiveBinarySearch(array, element, 0, middle - 1) | |
} else { | |
return recursiveBinarySearch(array, element, middle + 1, end) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment