Skip to content

Instantly share code, notes, and snippets.

@Toomean
Created August 29, 2019 20:55
Show Gist options
  • Save Toomean/afd7f33f41c55890631e517f06be5c34 to your computer and use it in GitHub Desktop.
Save Toomean/afd7f33f41c55890631e517f06be5c34 to your computer and use it in GitHub Desktop.
Javascript function that implements binary search algorithm
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