2

How can I fix the code - the algorithm finds the searched number for all the cases, except for when you try to find 0 indexed number or in my case search_num = 1.

list1 = [1, 3, 4, 5, 19, 21, 52, 100, 152]
search_num = 1

def binarySearch(array, number):

    lower_b_index = 0
    upper_b_index = len(array) - 1

    while lower_b_index <= upper_b_index:

        mid_point = (lower_b_index + upper_b_index) // 2

        if array[mid_point] == number:
            return mid_point
        elif array[lower_b_index] == number:
            return lower_b_index
        else:
            if array[mid_point] < number:
                lower_b_index = mid_point + 1
            else: 
                upper_b_index = mid_point - 1 

    return False

a1 = binarySearch(list1, search_num)

if a1:
    print("The searched position: ", a1 + 1)
else:
    print("Not Found!")

1 Answer 1

2

Your problem isn't in your binarySearch algo it's your if statement after.

You algo returns a1 = 0 which is correct and your checking if 0 and 0 is boolean to False

An easy fix would be to return None and check if a1 is not None

list1 = [1, 3, 4, 5, 19, 21, 52, 100, 152]
search_num = 1

def binarySearch(array, number):

    lower_b_index = 0
    upper_b_index = len(array) - 1

    while lower_b_index <= upper_b_index:

        mid_point = (lower_b_index + upper_b_index) // 2

        if array[mid_point] == number:
            return mid_point
        elif array[lower_b_index] == number:
            return lower_b_index
        else:
            if array[mid_point] < number:
                lower_b_index = mid_point + 1
            else: 
                upper_b_index = mid_point - 1 

    return None  # Change here

a1 = binarySearch(list1, search_num)

if a1 is not None:  # Change here
    print("The searched position: ", a1 + 1)
else:
    print("Not Found!")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks) Helped alot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.