Skip to content

Instantly share code, notes, and snippets.

@xesjkeee
Created January 28, 2019 10:53
Show Gist options
  • Save xesjkeee/551765cf835294e1a679ce1fb05f6e7f to your computer and use it in GitHub Desktop.
Save xesjkeee/551765cf835294e1a679ce1fb05f6e7f to your computer and use it in GitHub Desktop.
Binary Search | TypeScript
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