Created
April 23, 2016 01:18
-
-
Save AntonisFK/32538e744d6a8bea0f4dee30b794033c to your computer and use it in GitHub Desktop.
BinarySearch 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
function binarySearch(array, key) { | |
var lo = 0, | |
hi = array.length - 1, | |
mid, | |
element; | |
while (lo <= hi) { | |
mid = Math.floor((lo + hi) / 2); | |
element = array[mid]; | |
if (element < key) { | |
lo = mid + 1; | |
console.log(lo,"elment < key", mid, array[mid]); | |
} else if (element > key) { | |
hi = mid - 1; | |
console.log(hi, "element > key", mid, array[mid]); | |
} else { | |
return mid; | |
} | |
} | |
return -1; | |
} | |
var arr = [1,2,3,4,6,7,8,9,10,11,13,15,17,20]; | |
binarySearch(arr, 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment