Posted By

jatkins on 07/11/17


Tagged

search algorithm linear nearest


Versions (?)

Nearest k / linear search for sorted arrays


 / Published in: JavaScript
 

Released into the public domain by Josh Atkins, 2017. Can't see any bugs in this. Of course, you could use binary search if you wanted.

  1. function nearestK(k, haystack) {
  2. var smallestDistance = Infinity, distance, closest;
  3. for (var i = 0, length = haystack.length; i < length; i++) {
  4. distance = Math.abs(haystack[i] - k);
  5. if (distance <= smallestDistance) {
  6. smallestDistance = distance;
  7. closest = haystack[i];
  8. }
  9. if (haystack[i] > k) {
  10. break;
  11. }
  12. }
  13. return closest;
  14. }

Report this snippet  

You need to login to post a comment.