Created
July 7, 2023 19:16
-
-
Save Git-I985/80a99c429014e88024a31bb37d5c3488 to your computer and use it in GitHub Desktop.
phonebook binary search js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// binary search by key | |
const binarySearch = (phonebook, searchName) => { | |
if(phonebook.length === 0) { | |
return 'Phonebook is empty!' | |
} | |
let left = 0 | |
let right = phonebook.length - 1 | |
while(left <= right) { | |
let middlePersonIndex = Math.round((left + right) / 2) | |
let middlePerson = phonebook[middlePersonIndex] | |
if (middlePerson.name === searchName) { | |
return middlePerson.number | |
} | |
if (searchName < middlePerson.name) { | |
right = middlePersonIndex - 1 | |
} | |
if (searchName > middlePerson.name) { | |
left = middlePersonIndex + 1 | |
} | |
} | |
return 'Name not found!' | |
} | |
export default binarySearch |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment