Incorrect binary search code in python

I am constantly getting the wrong output in my binary search program. The output is always None even when the key element is present. Have a look at my code and help, please.

guess=1
def binary_search[n,key]:
    low=0
    high=len[n]-1
    
    while[low key then you need to decrease the guess my setting high=mid-1 and increase the guess with low=mid+1 if guess x:

            return binary_search[arr, low, mid - 1, x]

        else:

            return binary_search[arr, mid + 1, high, x]

    else:

        return -1

arr = [ 2, 3, 4, 10, 40 ]

x = 10

result = binary_search[arr, 0, len[arr]-1, x]

if result != -1:

    print["Element is present at index", str[result]]

else:

    print["Element is not present in array"]

Output:  

Element is present at index 3

Time Complexity: O[log n]

Auxiliary Space: O[logn]     [NOTE: Recursion creates Call Stack]

Iterative:
 

Python3

def binary_search[arr, x]:

    low = 0

    high = len[arr] - 1

    mid = 0

    while low x:

            high = mid - 1

        else:

            return mid

    return -1

arr = [ 2, 3, 4, 10, 40 ]

x = 10

result = binary_search[arr, x]

if result != -1:

    print["Element is present at index", str[result]]

else:

    print["Element is not present in array"]

Output:  

Element is present at index 3

Time Complexity: O[log n]

Auxiliary Space: O[1]
Please refer to the article Binary Search for more details!
 


What is binary search Explain with example in Python?

Binary search is a searching algorithm which is used to search an element from a sorted array. It cannot be used to search from an unsorted array. Binary search is an efficient algorithm and is better than linear search in terms of time complexity. The time complexity of linear search is O[n].

How do you write a binary search program in Python?

Implement a Binary Search in Python.
# Iterative Binary Search Function method Python Implementation..
# It returns index of n in given list1 if present,.
# else returns -1..
def binary_search[list1, n]:.
low = 0..
high = len[list1] - 1..
mid = 0..
while low

Chủ Đề