Advertisement
P_Donchev

Khan Academy - Binary Search

Dec 17th, 2020
72
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.     var numberOfGuesses = 1;
  8.    
  9.     while (max >= min) {
  10.         guess = Math.floor((min + max) / 2);
  11.        
  12.         if (array[guess] === targetValue) {
  13.             return guess;
  14.         } else if (array[guess] < targetValue) {
  15.             min = guess + 1;
  16.         } else{
  17.             max = guess - 1;
  18.         }
  19.        
  20.         numberOfGuesses++;
  21.     }
  22.  
  23.  
  24.     return -1;
  25. };
  26.  
  27. var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,
  28.         41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
  29.  
  30. var result = doSearch(primes, 73);
  31. println("Found prime at index " + result);
  32.  
  33. Program.assertEqual(doSearch(primes, 73), 20);
  34. Program.assertEqual(doSearch(primes, 41), 1);
  35. Program.assertEqual(doSearch(primes, 41), 1);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement