Guest User

Untitled

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