Skip to content

Instantly share code, notes, and snippets.

@chalu
Last active March 1, 2017 11:14
Show Gist options
  • Save chalu/fecd9ec5704fb010b8f2c144d7833bcc to your computer and use it in GitHub Desktop.
Save chalu/fecd9ec5704fb010b8f2c144d7833bcc to your computer and use it in GitHub Desktop.
1st Attempt - JavaScript Binary Search (Done in Lagos Traffic!)
let binarySearch = (haystack, needle) => {
let allNums = haystack.every( entry => !isNaN(entry) );
let needleIsNum = !isNaN(needle);
if( needleIsNum && allNums){
// prepare inputs
haystack = haystack.sort( (a, b) => a - b );
// define Algol
let bSearchr = (aHaystack) => {
let stackLen = aHaystack.length;
let midIndex = Math.floor( stackLen / 2 );
let midItem = aHaystack[ midIndex ];
console.log("%s items, [%s] in the middle @ index %s", stackLen, midItem, midIndex);
if(needle === midItem){
let found = haystack.indexOf(needle);
console.log("matched needle %s @ %s", needle, found);
return found;
}
// We can't just keep reducing the array.
// At some point, with a tiny array,
// very likely to contain our "needle",
// we can "search" for "needle".
// Also need an algorithmic way
// to dtermine 3.
if(stackLen <= 3){
let found = haystack.indexOf(needle);
console.log("found needle %s @ %s", needle, found);
return found;
}
let start = -1, end = -1;
if(needle < midItem){
start = 0;
end = midIndex;
console.log('branching left ...');
}else if (needle > midItem){
start = midIndex + 1;
end = stackLen;
console.log('branching right ...');
}
let aReducedHaystack = aHaystack.slice(start, end);
return bSearchr(aReducedHaystack);
};
let found = bSearchr(haystack);
console.log("Found %s @ index %s in [%s]", needle, found, haystack.join(", "));
return found;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment