Advertisement
Guest User

Untitled

a guest
Feb 26th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.66 KB | None | 0 0
  1. /* Returns either the index of the location in the array,
  2. or -1 if the array did not contain the targetValue */
  3. var doSearch = function(array, targetValue) {
  4. var min = 0;
  5. var max = array.length - 1;
  6. var guess;
  7. while(max>=min){
  8. guess = Math.floor((max+min)/2);
  9. if(array[guess]===targetValue){return guess;}
  10. else if(array[guess]<targetValue){min=guess+1;}
  11. else{max=guess-1;}
  12. }
  13. return -1;
  14. };
  15.  
  16. var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,
  17. 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
  18.  
  19. var result = doSearch(primes, 73);
  20. println("Found prime at index " + result);
  21.  
  22. Program.assertEqual(doSearch(primes, 73), 20);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement