Created
January 28, 2019 10:53
-
-
Save xesjkeee/551765cf835294e1a679ce1fb05f6e7f to your computer and use it in GitHub Desktop.
Binary Search | TypeScript
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
const binarySearch = (arr: number[], val: Number) => { | |
let start: number = 0, | |
end: number = arr.length - 1, | |
middle: number | |
while (start < end) { | |
middle = Math.floor((+start + +end) / 2) | |
if (val <= arr[middle]) { | |
end = middle | |
} else { | |
start = middle + 1 | |
} | |
} | |
if (arr[start] === val) return start | |
return -1 | |
} | |
const arr: number[] = [1, 2, 3, 4, 5, 6, 7, 12, 124, 12312, 123122] | |
console.log(binarySearch(arr, 123122)) // 10 | |
console.log(binarySearch(arr, 12312)) // 9 | |
console.log(binarySearch(arr, 2)) // 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment