Skip to content

Instantly share code, notes, and snippets.

@dciccale
Last active December 22, 2015 03:49
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 dciccale/6413107 to your computer and use it in GitHub Desktop.
Save dciccale/6413107 to your computer and use it in GitHub Desktop.
Binary search function done with 109 bytes of JavaScript

binarySearch

Tiny binary search done with 109 bytes of JavaScript.

/**
* @param a A list of items
* @param b An item to search its index inside the list of items
*/
function binarySearch(a, b) {
for (var c = 0, d = a.length, e; c <= d;) {
e = ~~((d + c) / 2);
if (a[e] === b) return e;
a[e] > b ? d = e - 1 : c = e + 1
}
return -1;
}
function(b,e){for(var c=0,d=b.length,a;c<=d;){a=~~((d+c)/2);if(b[a]===e)return a;b[a]>e?d=a-1:c=a+1}return-1}
<!doctype html>
<title>Demo</title>
<script>
var binarySearch = function(b,e){for(var c=0,d=b.length,a;c<=d;){a=~~((d+c)/2);if(b[a]===e)return a;b[a]>e?d=a-1:c=a+1}return-1};
var items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
var result = binarySearch(items, 'i');
console.log(result); // logs 8
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment