Posted By

eryoav on 02/25/12


Tagged

algorithm


Versions (?)

Binary Search


 / Published in: JavaScript
 

simple binary search algorithm

  1. (function () {
  2.  
  3. // must be sorted array.
  4. var aList = [2, 6, 9, 32, 33, 45, 47, 65];
  5.  
  6. nElemToFind = 6,
  7. nMinRange = 0,
  8. nMaxRange = aList.length-1,
  9. bResult = false;
  10.  
  11. while (nMinRange <= nMaxRange)
  12. {
  13. var nMid = Math.floor((nMinRange + nMaxRange) / 2);
  14.  
  15. if (nElemToFind === aList[nMid]) {
  16. bResult = true;
  17. console.log(bResult);
  18. return;
  19. }
  20. else if (aList[nMid] > nElemToFind) {
  21. nMaxRange = nMid-1;
  22. }
  23. else if (aList[nMid] < nElemToFind) {
  24. nMinRange = nMid+1;
  25. }
  26. }
  27. console.log(bResult)
  28.  
  29. })();

Report this snippet  

You need to login to post a comment.