Paste Search Dynamic
Recent pastes
search arr x
  1. function search(arr, x)
  2. {
  3.     let i = 0;
  4.     let j = arr.length;
  5.     while (i !== j)
  6.     {
  7.         let m = Math.floor((i + j) / 2);
  8.         if (x === arr[m])
  9.             return m;
  10.         if (x < arr[m])
  11.             j = m;
  12.         else
  13.             i = m + 1;
  14.     }
  15.     return null;
  16. }
  17.  
  18.  
  19. let items = [ 2, 3, 5, 7, 11, 13, 17 ];
  20.  
  21. console.log(search(items, 1));
  22. //print null
  23. console.log(search(items, 7));
  24. //print 3
  25. console.log(search(items, 19));
  26. //print null
  27.  
  28. // *** simplified speed test ***
  29.  
  30. let i = 0;
  31. items = Array
  32.   .apply(null, Array(10000))
  33.   .map(() => ++i );
  34. let count = 10000;
  35.  
  36. let start = new Date();
  37.  
  38. for (i = 0; i < count; i++)
  39.   search(items, 7777);
  40.  
  41. let milliseconds = (new Date()) - start;
  42.  
  43. console.log(milliseconds * 100);
  44. // about 5 milliseconds
Parsed in 0.003 seconds