Created
April 7, 2016 00:31
-
-
Save AntonisFK/8d1577d2138c0244aeb22149de2dd473 to your computer and use it in GitHub Desktop.
Binary Search of an array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// var arr = [-90,-19,0,2,12,29,33,190,320]; | |
// rBS(arr, 5) => false | |
// rBS(arr, 12) => 4 | |
// rBS(arr, 0) => 2 | |
// rBS(arr, 190) => 7 | |
var rBs = function(arr,num){ | |
var max, min; | |
if(num > arr[Math.floor(arr/2)] ){ | |
max = arr.length-1; | |
min = Math.floor(arr.length/2); | |
} | |
else{ | |
min = 0; | |
max = Math.floor(arr.length/2); | |
} | |
for(var i=min; i< Math.floor(arr.length/2); i++){ | |
if(arr[min] < num){ | |
min ++; | |
} | |
if(arr[max] > num ){ | |
max --; | |
} | |
} | |
if( max === min){ | |
return min; | |
} else if(max<min){ | |
return false ; | |
} | |
}; | |
rBs([-90,-19,0,2,12,29,33,190,320], 12); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment