Skip to content

Instantly share code, notes, and snippets.

@Keireira
Last active February 7, 2025 19:20
Show Gist options
  • Select an option

  • Save Keireira/7f70e467ad4361cd0069f09a337adba5 to your computer and use it in GitHub Desktop.

Select an option

Save Keireira/7f70e467ad4361cd0069f09a337adba5 to your computer and use it in GitHub Desktop.
const comparatorF = (element, needle) => element - needle
const binarySearch = (list, needle, comparator = comparatorF) => {
if (!needle || !list) return null
let min = 0
let max = list.length - 1
while (min <= max) {
const mid = Math.floor(min + (max - min) / 2)
const quess = list[mid]
const compared = comparator(quess, needle)
if (compared === 0) {
return quess
} else if (compared > 0) {
max = mid - 1
} else {
min = mid + 1
}
}
return null
}
export default binarySearch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment