Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
_javascript-findBinary.js - also has findIndexBinary
function findBinary(arr, num, ixmin=0, ixmax) {
// arr MUST be sorted!!! and only numbers!!! duh! see: https://en.wikipedia.org/wiki/Binary_search_algorithm
// ixmin and ixmax are programtic use only, meaning devuser should NEVER supply value for it
if (ixmax === undefined) ixmax = arr.length;
let ixmid = Math.floor((ixmax-ixmin)/2) + ixmin;
let elmid = arr[ixmid];
if (elmid === num) return elmid;
else {
if (ixmax - ixmin === 1) return null; // not found
return num < elmid ? findBinary(arr, num, ixmin, ixmid) : findBinary(arr, num, ixmid, ixmax);
}
}
function findIndexBinary(arr, num, ixmin=0, ixmax) {
// arr MUST be sorted!!! and only numbers!!! duh! see: https://en.wikipedia.org/wiki/Binary_search_algorithm
// ixmin and ixmax are programtic use only, meaning devuser should NEVER supply value for it
if (ixmax === undefined) ixmax = arr.length;
let ixmid = Math.floor((ixmax-ixmin)/2) + ixmin;
let elmid = arr[ixmid];
if (elmid === num) return ixmid;
else {
if (ixmax - ixmin === 1) return null; // not found
return num < elmid ? findIndexBinary(arr, num, ixmin, ixmid) : findIndexBinary(arr, num, ixmid, ixmax);
}
}
@Noitidart
Owner

README

Rev1

  • Has all the console logging and recursion short circuiter

Rev2

  • Cleaned up, short cut braces, added findIndexBinary
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment