Skip to content
Advertisement

Binary search through string tuple in list

I’m trying to do a binary search through a list of tuples, when I give a inputq = “BB”, it is not show a correct search.

This is my data:

JavaScript

This my code:

JavaScript

when I give inputq = “BB” the output it always show like this: (‘BF’, ‘Burkina Faso’, 13.0, -2.0)

I would like to show my output like this when I give inputq = “BB”

(‘BB’, ‘Barbados’, 13.17, -59.53) how to do that?

Advertisement

Answer

I found two main problems with your algorithm. First, as @gog points out, you are calculating res as a boolean, but then are comparing it with integers. The other thing is that you are comparing the term arr[m] to the target, as though that term refers to the equivalent value in the data structure. It does not. Rather, it refers to the entire tuple. What you want instead is arr[m][0].

Fixing those two issues, and maybe a few small issues, here’s a new version of your code that seems to correctly find any value in the array:

JavaScript

Result (when the original function is replaced with this new version in the original code):

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement