Skip to content

Instantly share code, notes, and snippets.

@F1LT3R
Last active August 27, 2017 00:25
Show Gist options
  • Save F1LT3R/c8b6fbd5ba5aaa89e16510a9a5b13d1f to your computer and use it in GitHub Desktop.
Save F1LT3R/c8b6fbd5ba5aaa89e16510a9a5b13d1f to your computer and use it in GitHub Desktop.
Binary Search Typescript
enum FailExits {
ologn,
nochop
}
let exit = FailExits.ologn
let iterCount:number
let maxIterations: number
const compare = (target: number, ary: number[], start: number, end: number): number[] | number | boolean => {
const range = end - start
const midPoint = start + (range / 2)
const midIndex = Math.floor(midPoint)
const midValue = ary[midIndex]
// Fail Exit Strategy 1: Max iterations is set to O(log(n))
if (iterCount > maxIterations && exit === FailExits.ologn) {
return false
}
// Found index when mid = target
if (midValue === target) {
return midIndex
}
// Fail Exit Strategy 2: startIndex = midIndex
if (start === midIndex && exit === FailExits.nochop) {
return false
}
// Chop Left
if (target < midValue) {
start = start
end = midIndex
}
// Chop Right
if (target > midValue) {
start = midIndex
}
iterCount += 1
return compare(target, ary, start, end)
}
const search = (target: number, ary: number[]): number | boolean => {
maxIterations = Math.ceil(Math['log2'](ary.length)) + 1
iterCount = 0
const start = 0
const end = ary.length
const foundIndex = compare(target, ary, start, end)
if (typeof foundIndex === 'number') {
return foundIndex
}
return false
}
let myAry: number[] = [
1, 2, 3, 4, 6, 7, 8, 10, 13, 14, 18, 19, 21, 24, 37, 40, 45, 71
]
const start = (target: number): void => {
const foundIndex = search(target, myAry)
if (foundIndex) {
console.log(`The target: ${target} was found at index: ${foundIndex}`)
} else {
console.log(`The target: ${target} was not found in this array`)
}
}
start(11)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment