Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Code to implement iterative Binary Search

# code to implement iterative Binary Search.
def binarySearchIterative(arr, l, r, x):
	while l <= r:
		mid = l + (r - l) // 2;
		if arr[mid] == x:
			return mid
		elif arr[mid] < x:
			l = mid + 1
		else:
			r = mid - 1
	return -1
arr = [ 4, 9, 8, 20, 80 ]
find = 80
result = binarySearchIterative(arr, 0, len(arr)-1, find)
if result != -1:
	print ("Element is present at index % d" % result)
else:
	print ("Element is not present in array")
Comment

iterative bin search

"""Binary Search
Iterative
"""

def bin_iter(lst, item, low=0, high=None):
    if high is None:
        high = len(lst) - 1
    while low <= high:
        mid = (low + high) // 2
        if item > lst[mid]: # To the left
            low = mid + 1
        elif item < lst[mid]: # To the right
            high = mid - 1
        else: # Found
            return mid
    return []  # Not found
Comment

PREVIOUS NEXT
Code Example
Python :: how to specify variable type in python 
Python :: basic flask app python 
Python :: python make 1d array from n-d array 
Python :: Modify a Python interpreter 
Python :: convert str to datetime 
Python :: python backslash in string 
Python :: python turtle shapes 
Python :: modern tkinter 
Python :: device gpu pytorch 
Python :: delimiter pandas 
Python :: noise reduction filter images python 
Python :: how to change the colour of axes in matplotlin 
Python :: stack error: command failed: import sys; print "%s.%s.%s" % sys.version_info[:3]; 
Python :: save seaborn lmplot 
Python :: create an array with a range of elements 
Python :: for loop example python 3 
Python :: jupyterlab interactive plot 
Python :: What does if __name_=="_main__": do? 
Python :: Add Cog to bot in Discord.py 
Python :: make_response is not defined django 
Python :: pandas selection row/columns 
Python :: ValueError: Shapes (None, 1) and (None, 3) are incompatible 
Python :: python how to print something at a specific place 
Python :: how to change templates folder in flask 
Python :: python index of lowest value in list 
Python :: mean python 
Python :: if statement in python 
Python :: how to remove an element from a list in python 
Python :: listas en python 
Python :: python string interpolation 
ADD CONTENT
Topic
Content
Source link
Name
6+8 =