Created
December 18, 2014 14:47
-
-
Save thenormalsquid/384afa216e78354ad1c1 to your computer and use it in GitHub Desktop.
blackdeck
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 = [1,2,3,4,5,6,7,8,9,10] | |
function binarySearch(elem, arr) { | |
//loop through array and partition | |
var max = arr.length - 1, | |
min = 0, | |
mid = arr[Math.floor(len/2)]; | |
if (arr.length === 0){ | |
return "Key not found, array is empty"; | |
} | |
else if (elem === arr[max]){ | |
return max; | |
} | |
else if (elem === arr[min]) { | |
return 0; | |
} | |
//perform the binary search here | |
else { | |
while(min < max) { | |
if(elem > arr[mid]) { | |
//move your min up, niqqa | |
min = mid + 1; | |
} | |
else { | |
//partition up to mid | |
max = mid; | |
} | |
} | |
if((arr[min] === elem)&&(max === min)){ | |
return min; | |
} else { | |
return "Key not found in array, you're searching for shit"; | |
} | |
} | |
} | |
binarySearch(4, arr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment