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 binary 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 :: alphabetical 
Python :: HOW TO CREATE A DATETIME LIST QUICK 
Python :: class python __call__ 
Python :: group a dataset 
Python :: dict to list python 
Python :: NumPy fliplr Syntax 
Python :: spacy create tokenizer 
Python :: write code in python to Open all links on a page in separate browser tabs 
Python :: Python NumPy ndarray.T Example to convert an array 
Python :: python use negation with maskedarray 
Python :: run a shell script from python 
Python :: python indian currency formatter 
Python :: python code to increase cpu utilization 
Python :: how to python string up 
Python :: standard streams with python3 
Python :: python avg 
Python :: create django model field based on another field 
Python :: declare array python 
Python :: upload folder to s3 bucket python 
Python :: numpy variance 
Python :: importing a python file from another folder 
Python :: pipeline model coefficients 
Python :: Adding two lists using map() and Lamda Function 
Python :: how to add items to a set in python 
Python :: pass query params django template 
Python :: re.search 
Python :: do while python using dates 
Python :: assignment 6.5 python for everybody 
Python :: python regex find single character 
Python :: ValueError: All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters 
ADD CONTENT
Topic
Content
Source link
Name
8+8 =