Last active
February 19, 2017 05:01
-
-
Save Noitidart/10880dc0a5c53c2ae3e499401a03cf54 to your computer and use it in GitHub Desktop.
_javascript-findBinary.js - also has findIndexBinary
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 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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
README
Rev1
Rev2
findIndexBinary