Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Binary Search Output giving wrong answer

This is my code:

def binary_search(keys, query):
    low, high = 0, 0
    while low <= high:
        midpoint = low + (high - low) // 2
        if query == keys[midpoint]:
            return midpoint
        elif keys[midpoint] > query:
            high = midpoint - 1 
        else:
            low = midpoint + 1
    return -1       
           

if __name__ == '__main__':
    num_keys = int(input())
    input_keys = list(map(int, input().split()))
    assert len(input_keys) == num_keys

    num_queries = int(input())
    input_queries = list(map(int, input().split()))
    assert len(input_queries) == num_queries

    for q in input_queries:
        print(binary_search(input_keys, q), end=' ')

I am inputting:

5
1 5 8 12 13
5
8 1 23 1 11

I should be getting this as output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

2 0 -1 0 -1

but I am getting this instead:

-1 0 -1 0 -1

>Solution :

You are starting with both low and high equal to 0, which doesn’t make sense. Change the first two lines to the following:

low, high = 0, len(keys)
while low < high:
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading