Home > Problem, Projects/Experiments, Python > Python Project: Binary Search

## Python Project: Binary Search

Python: Binary Search

Binary Search

Definition:

Binary Search is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the middle element of the array.

In this code we are writing a Python code to find the target in a sorted given array and get its position without using any python math packages.

The case: We have an Array (arr=[2,3,5,6,8,10,11,13,15,16,19]) our target is 13, so we want the position of 13.

We are setting the first position as (pos_s=0) and the end position as (pos_e= the length of the array -1) and we will use recursive function.

Recursive Function: is a computer function or procedure that calling it self

The Code:

arr=[2,3,5,6,8,10,11,13,15,16,19]
target=11
pos_s =0
pos_e=int(len(arr)-1)
midarr =0
def bsearch(arr,target,pos_s,pos_e):

midarr=(pos_s+pos_e)/2

if arr[midarr] < target:

pos_s = midarr +1

bsearch(arr,target,pos_s,pos_e)

elif arr[midarr] > target:

pos_e = midarr -1

bsearch(arr,target,pos_s,pos_e)

elif arr[midarr] == target:

print(‘The target was: ‘,target, ‘ The key of our target is: ‘,midarr)

return

print(arr)
# Call the functin
bsearch(arr,target,pos_s,pos_e)