In: Computer Science
#This function "binarySearchPythonCode" identifies the elements which is present in the start and end values
def binarySearchPythonCode(list, Element, startElement, endElement):
#Variable which describes whether the element is present or not
isPresent = False
#condition check for start and end values
while startElement<=endElement and not isPresent:
#logic for calculating the mid value
midElement = startElement + endElement//2
# if condition which checks whether the mid value is same as element to be searched
if list[midElement] == Element:
#if condition satisfies it changes the flag to true
isPresent = True
#else condition which displays the end value and start value
else:
# if condition checks whether the element is present in the list or not
if Element < list[midElement]:
#if the element is present it calculates the end value
endElement = midElement-1
#else it will calculate the start value
else:
startElement = midElement+1
# returns the flag bit
return isPresent
list = [10, 20, 30, 40, 50, 60, 70, 80, 90]
print(binarySearchPythonCode(list, 40, 10, 90))
python code gives error, index error, how to fix?
Problem With Code:
=====================
=> Binary search logic is based on index but you are passing start and end elements instead of their indexes.
=> The function is recursive but in current code it calls only once. It is not called recursively after updating firstElement index and endElement.
Updated Solution:
=====================
def binarySearchPythonCode(list, Element, startElement, endElement):
#Variable which describes whether the element is present or
not
isPresent = False
#condition check for start and end values
while startElement<=endElement and not isPresent:
#logic for calculating the mid value
midElement = (startElement + endElement) // 2
# if condition which checks whether the mid value is same as
element to be searched
if list[midElement] == Element:
#if condition satisfies it changes the flag to true
isPresent = True
#else condition which displays the end value and start value
else:
# if condition checks whether the element is present in the list or
not
if Element < list[midElement]:
#if the element is present it calculates the end value
endElement = midElement-1
binarySearchPythonCode(list, Element, startElement,
endElement)
#else it will calculate the start value
else:
startElement = midElement+1
binarySearchPythonCode(list, Element, startElement,
endElement)
# returns the flag bit
return isPresent
list = [10, 20, 30, 40, 50, 60, 70, 80, 90]
print(binarySearchPythonCode(list, 40, 0, len(list)-1))
Description:
==============
=> The above solution solves the problems that I have mentioned in the beginning.
=> The search for particular element in list using binary search recursively.