HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Binary search of an integer array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arrayintegerbinarysearch

Problem

I'm a beginner. This is my implementation of binary search algorithm in Python. Please review my code and give your valuable inputs for further improvements on overall coding style, rare cases etc.

def binary_search(arr,value):
    left = 0
    right = len(arr) - 1
    while(left  arr[mid]:
            left = mid + 1

    return -1

def print_binary_search(arr,value):
    pos = binary_search(arr,value)
    if pos is -1:
        print("Element not found")
    else:
        print("Element found in the positon " +str(pos))

def test1():
    arr = [2,5,8,9,11,15,17,19,22,26,29,33,56]
    value = 56
    print_binary_search(arr,value)

def test2():
    arr = [2,5,8,9,11,15,17,19,22,26,29,33,56]
    value = 59
    print_binary_search(arr,value)

test1()
test2()

Solution

-
if arr[mid] is value:

You don't want to compare two integers with is, which compares identity. Use == instead. is will break your code when using large or small numbers (\$256\$).

For example, using is with this "test" function:

def test1():
    arr = list(range(257, 270))
    value = 260
    print_binary_search(arr, value)


Results with an infinite loop.

Using == works as expected and returns 3.

The reason is that Python uses integer caching for the range \$[-5, 256]\$.

And some PEP8 nitpicking:

-
`while(left

-
You are missing some whitespaces after commas in function definition, function calls, list literals and around operators.

For example, your code should look like this (relevant lines only):

def print_binary_search(arr, value):

#######

pos = binary_search(arr, value)

#######

arr = [2, 5, 8, 9, 11, 15, 17, 19, 22, 26, 29, 33, 56]

#######

print("Element found in the position " + str(pos))

Code Snippets

def test1():
    arr = list(range(257, 270))
    value = 260
    print_binary_search(arr, value)
while left <= right:
def print_binary_search(arr, value):

#######

pos = binary_search(arr, value)

#######

arr = [2, 5, 8, 9, 11, 15, 17, 19, 22, 26, 29, 33, 56]

#######

print("Element found in the position " + str(pos))

Context

StackExchange Code Review Q#138675, answer score: 5

Revisions (0)

No revisions yet.