Nikita
Nikita

Reputation: 35

In my binary search algorithm, Python doesn't find 0 indexed member in the list

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!")

Upvotes: 2

Views: 50

Answers (1)

Kenan
Kenan

Reputation: 14094

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!")

Upvotes: 2

Related Questions