Created
August 29, 2019 20:55
-
-
Save Toomean/afd7f33f41c55890631e517f06be5c34 to your computer and use it in GitHub Desktop.
Javascript function that implements binary search algorithm
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
function binarySearch( array, item ) { | |
let low = 0; | |
let high = array.length - 1; | |
while ( low <= high ) { | |
let mid = Math.floor( ( low + high ) / 2 ); | |
let guess = array[ mid ]; | |
if ( guess > item ) { | |
high = mid - 1; | |
} | |
else if ( guess < item ) { | |
low = mid + 1; | |
} | |
else { | |
return guess; | |
} | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment