Last active
November 23, 2017 08:33
-
-
Save xremix/3412799b0ed4992052f5805a8fb72e41 to your computer and use it in GitHub Desktop.
Binary Search JS
This file contains 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> | |
<html> | |
<head> | |
<title></title> | |
<script type="text/javascript"> | |
'use strict'; | |
var data = []; | |
for (var i = 0; i < 999999; i++) { | |
data.push(i); | |
} | |
function binSearch(arrData, searchVal){ | |
var fromSearch = 0; | |
var toSearch = arrData.length-1; | |
while(true){ | |
var half = parseInt((fromSearch + toSearch) / 2); | |
if(arrData[half] < searchVal){ | |
fromSearch = half; | |
if(half+1 == toSearch){ | |
return toSearch; | |
} | |
}else if(arrData[half] > searchVal){ | |
toSearch = half; | |
}else if(arrData[half] === searchVal){ | |
return half; | |
}else{ | |
return -1; | |
} | |
} | |
return -1; | |
} | |
console.time("asdf"); | |
console.log(data[binSearch(data, 123123)]); | |
console.timeEnd("asdf"); | |
</script> | |
</head> | |
<body> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment