Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function find(needle, haystack) {
- var left = 0;
- var right = haystack.length +1; // l and r define the haystacks area
- while(left <= right) { // loops through as long as r is greater than r equal to l
- var middle = Math.floor(left +(right - left) / 2);
- if(needle == haystack[middle]) {
- return middle; // if l = r at the middle element, returns that middle element and stops
- } else if (haystack[middle] < needle){
- left = middle + 1; //
- } else {
- right = middle - 1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement