Guest User

Untitled

a guest
Nov 20th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.80 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.  
  4. var doSearch = function(array, targetValue) {
  5. var guess;
  6. var min = 0;
  7. var max = array.length - 1;
  8. var n = 0;
  9.  
  10. while(min <= max){
  11. guess = Math.floor((min + max) /2);
  12. n++;
  13. if(array[guess] === targetValue)
  14. println(array[guess]);
  15. println("Guesses:" +n);
  16. return guess;
  17. else if(array[guess] < targetValue)
  18. min = guess + 1;
  19. else
  20. max = guess - 1;
  21. }
  22. return -1;
  23. }
  24.  
  25. var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
  26.  
  27. var result = doSearch(primes, 73);
  28.  
  29. println("Found prime at index " + result);
  30. Program.assertEqual(doSearch(primes, 73), 20);
  31. Program.assertEqual(doSearch(primes, 2), 0);
  32. Program.assertEqual(doSearch(primes, 3), 1);
Add Comment
Please, Sign In to add comment