Advertisement
Guest User

Untitled

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