Drill 26: Improve it — Binary search
Add one improvement and explain the benefit.
What you will be able to do
- Add one improvement and explain the benefit.
Practice task
Add one improvement and explain the benefit.
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
EasyWrite your answer
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 inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.