Skip to content

Instantly share code, notes, and snippets.

@Noitidart
Last active February 19, 2017 05:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Noitidart/10880dc0a5c53c2ae3e499401a03cf54 to your computer and use it in GitHub Desktop.
Save Noitidart/10880dc0a5c53c2ae3e499401a03cf54 to your computer and use it in GitHub Desktop.
_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
Copy link
Author

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