Advertisement
Guest User

Untitled

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