Drill 6: Improve it — Binary search

Add one improvement and explain the benefit.

Intermediate 5 min read Lesson 63 of 300 Challenge included
What you will be able to do
  • Add one improvement and explain the benefit.

Practice task

Add one improvement and explain the benefit.

binary-search.jsJavaScript
function binarySearch(sorted, target) {
  let low = 0
  let high = sorted.length - 1

  while (low <= high) {
    const mid = Math.floor((low + high) / 2)
    if (sorted[mid] === target) return mid
    if (sorted[mid] < target) low = mid + 1
    else high = mid - 1
  }
  return -1
}

function lowerBound(sorted, target) {
  let low = 0
  let high = sorted.length
  while (low < high) {
    const mid = Math.floor((low + high) / 2)
    if (sorted[mid] < target) low = mid + 1
    else high = mid
  }
  return low
}

console.log(binarySearch([1, 3, 5, 7, 9], 7))
console.log(lowerBound([1, 3, 3, 3, 5], 3))
Your turn

Write your answer

Easy

Add one improvement and explain the benefit.

TEXT · starter
Your answer…
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 63 of 300 · 0% of course