Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

Python binary search algorithm

def binary_search(arr, x):
    low = 0
    high = len(arr) - 1
    mid = 0

    while low <= high:
        mid = (high + low) // 2
		
		// if index of the arr given by the mid isnt matching x,
		// Keep adding, else subtract one in order to get the correct mid
		// value.

        if arr[mid] < x:
            low = mid + 1
		
        elif arr[mid] > x:
            high = mid - 1
        
        else:
            return mid
    return -1

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

result = binary_search(arr, x)
if result != -1:
    print("Element is presented at index" , str(result))
else:
    print("Element is not presented in array")
 
PREVIOUS NEXT
Tagged: #Python #binary #search #algorithm
ADD COMMENT
Topic
Name
3+5 =