Advertisement
Guest User

Untitled

a guest
Dec 18th, 2014
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. var arr = [1,2,3,4,5,6,7,8,9,10]
  2.  
  3. function binarySearch(elem, arr) {
  4. //loop through array and partition
  5. var max = arr.length - 1,
  6. min = 0,
  7. mid = arr[Math.floor(len/2)];
  8.  
  9. if (arr.length === 0){
  10. return "Key not found, array is empty";
  11. }
  12. else if (elem === arr[max]){
  13. return max;
  14. }
  15. else if (elem === arr[min]) {
  16. return 0;
  17. }
  18. //perform the binary search here
  19. else {
  20. while(min < max) {
  21. if(elem > arr[mid]) {
  22. //move your min up, niqqa
  23. min = mid + 1;
  24. }
  25. else {
  26. //partition up to mid
  27. max = mid;
  28. }
  29.  
  30. }
  31.  
  32. if((arr[min] === elem)&&(max === min)){
  33. return min;
  34. } else {
  35. return "Key not found in array, you're searching for shit";
  36. }
  37. }
  38. }
  39.  
  40. binarySearch(4, arr);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement