Skip to content

Instantly share code, notes, and snippets.

@binarymax
Forked from 140bytes/LICENSE.txt
Created May 27, 2011 15:21
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save binarymax/995468 to your computer and use it in GitHub Desktop.
Save binarymax/995468 to your computer and use it in GitHub Desktop.
Binary Search
/*
*
* Binary Search algorithm
* pass in sorted array 'a', and item to find 'b'
* returns the index if found, -1 otherwise (same as Array indexOf)
*
*/
function(
a, //Array parameter
b, //Item to find
c, //placeholder: lower bound
d, //placeholder: upper bound
e //placeholder: current index
){
for(c=0,d=a.length; //init lower and upper bounds
c<=d; //until lower and upper converge
){
if(b>a[e=0|(c+d)/2])c=e+1; //set index to halfway between upper and lower bounds.
//if index is less than the item, increase the lower bound.
else d=(b==a[e])?-2:e-1 //else if item found, set a flag(-2) and exit, otherwise decrease upper bound
}
return(d>-2)?-1:e //if flagged (-2), return the index, otherwise return -1
}
<!doctype html>
<html>
<head>
<title>Example</title>
<meta charset="utf-8" />
<script language="javascript" type="text/javascript">
var f = function(a,b,c,d,e){for(c=0,d=a.length;c<=d;){if(b>a[e=0|(c+d)/2])c=e+1;else d=(b==a[e])?-2:e-1}return(d>-2)?-1:e}
//load up a big sorted array:
for(var i=0,l=10000000,a=[],N=0;i<l;i++) a.push(i);
//Tests:
//binary search existing
N = f(a,l-92384);
console.log(N);
//indexOf existing
N = a.indexOf(l-92384);
console.log(N);
//binary search non-existing
N = f(a,-5);
console.log(N);
//indexOf non-existing
N = a.indexOf(-5);
console.log(N);
</script>
</head>
<body>
<div>Hi!</div>
</body>
</html>
function(a,b,c,d,e){for(c=0,d=a.length;c<=d;){if(b>a[e=0|(c+d)/2])c=e+1;else d=(b==a[e])?-2:e-1}return(d>-2)?-1:e}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Max Lovenheim Irwin <http://binarymax.com>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "Binary Search",
"description": "Binary Search for sorted array.",
"keywords": [
"binarysearch",
"search",
"find",
"indexOf"
]
}
@Yaffle
Copy link

Yaffle commented Jul 25, 2011

var test = [1,1,1,1];
console.log(f(test,1));
console.log(test.indexOf(1));

@binarymax
Copy link
Author

Oooops. Thanks Yaffle! Good thing I have 25 bytes to spare so I can fix it. I'll get to it this week.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment