Tiny binary search done with 109 bytes of JavaScript.
Last active
December 22, 2015 03:49
-
-
Save dciccale/6413107 to your computer and use it in GitHub Desktop.
Binary search function done with 109 bytes of JavaScript
This file contains hidden or 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
/** | |
* @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; | |
} |
This file contains hidden or 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(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} |
This file contains hidden or 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
<!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