Created
October 23, 2014 04:55
-
-
Save ultratoast/8911b5a1f6e40e25fcfa to your computer and use it in GitHub Desktop.
Javascript Binary Search for Integers
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 compareNum(a,b) { | |
| if (a < b) { | |
| return -1 | |
| } | |
| if (a > b) { | |
| return 1 | |
| } | |
| if (a == b) { | |
| return 0 | |
| } | |
| } | |
| function binSearch(arr, val, bool) { | |
| if (!bool) { | |
| arr = arr.sort(compareNum) | |
| } | |
| console.log('array: '+arr) | |
| var len = arr.length, | |
| half = Math.round(len/2), | |
| newArr | |
| console.log('half: '+arr[half]) | |
| if (arr[0] == val || arr[len - 1] == val || arr[half] == val) { | |
| console.log('Array has a match') | |
| return true | |
| } | |
| else if (val < arr[half]) { | |
| newArr = arr.slice(0,half) | |
| console.log('Value is below the median '+arr[half]) | |
| return binSearch(newArr,val,true) | |
| } | |
| else if (val > arr[half]) { | |
| newArr = arr.slice(half,len) | |
| console.log('Value is above the median '+arr[half]) | |
| return binSearch(newArr,val,true) | |
| } | |
| else { | |
| return false | |
| } | |
| } | |
| var myArray = [2,5,3,7,234,44,55.5,4,13,23] | |
| console.log(binSearch(myArray,24,false)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment