-
-
Save xrgranados/2618d2a4f44e4246f793fd3c9c4f6e55 to your computer and use it in GitHub Desktop.
Binary search
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
| Array.prototype.bsearch = function (x) { | |
| var min = 0, max = this.length; | |
| while (min <= max) { | |
| var mid = Math.floor((min + max) / 2), | |
| val = this[mid]; | |
| if (val === x) { | |
| return mid; | |
| } | |
| if (x > val) { | |
| min = mid + 1; | |
| } else { | |
| max = mid - 1; | |
| } | |
| } | |
| return -1; | |
| }; | |
| var Letters = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ]; | |
| alert(Letters.bsearch('A')); | |
| alert(Letters.bsearch('K')); | |
| alert(Letters.bsearch('Z')); | |
| alert(Letters.bsearch('Ъ')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment