Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
How to make binary search work with strings?

This binary search works with numbers, but not working with stings

 function binary_search(Array, key) {
   
   var middleIndex = Math.floor(Array.length / 2)
   var middleValue = numberArray[middleIndex]


   //base case key = middle element
   if (middleValue === key) return true


   else if (middleValue < key && Array.length > 1) {
       return binary_search(Array.splice(middleIndex, Array.length), key)
   }

   else if (middleValue > key && Array.length > 1)  {
      return binary_search(Array.splice(0, middleIndex), key)
   }

 else return false


}

If I give it numbers, it works:

console.log(binary_search([5,7,12,16,36,39,42,56,71], 36))
output: true

But not with strings:

console.log(binary_search(['cat', 'dog', 'bird', 'fish'], 'dog'))
result : flase

I understand the array must be presorted for this to work, but how to do this with strings?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Just as you say

I understand the array must be presorted for this to work

The array of strings you're passing in is not sorted, so binary search won't be possible. If you sort it first

['bird', 'cat', 'dog', 'fish']

then your current approach will already work, mostly, because === compares strings properly, and < and > lexiographically compares strings too (it works both for numbers and strings), with some caveats:

  • Use slice to extract a segment of an array, not splice, which will remove elements from the array (a mutation!) and return an array of those returned elements (not very intuitive)
  • You do not have a numberArray variable in scope, and you also shouldn't shadow the global Array. Use a different variable name, and use the same name everywhere in your function

function binary_search(arr, key) {
   const middleIndex = Math.floor(arr.length / 2)
   const middleValue = arr[middleIndex]
   if (middleValue === key) return true
   if (arr.length <= 1) return false;
   if (middleValue < key) {
       return binary_search(arr.slice(middleIndex), key)
   } else if (middleValue > key)  {
      return binary_search(arr.slice(0, middleIndex), key)
   }
   return false
}

console.log(binary_search(['bird', 'cat', 'dog', 'fish'], 'dog'));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!