Python- Binary Search(Recursive and Iterative)



          Binary Search(Recursive and Iterative) in Python


I am recently venturing into Python Language. Learning and comparing them with C# Skills I already possess. 

Here's my first code in Python where I will discuss about Binary Search using Iterative and Recursive Approach. 

As we know, Binary Search is one of the algorithm where user can search for an item in 

O(1) - Best Case 
O(log n)- Average Case 

Binary Search is based on Divide and Conquer Strategy.

Basic Concept of Binary Search. :  

    1)  You have a low index 
    2)  You have a high index. 
    3)  We calculate the mid value(initially: mid=low+high/2) and then depending on the whether the key that we are searching for is lesser than low or greater than high, we change the low and high values accordingly. 
    4) If the Key Value is less than Mid, we set high=mid-1;
    5) If the key value is greater than Mid, we set low=mid+1
    6) The above procedure is repeated from Step 2 to Step 5 until key is found 


# Binary search uses divide and conquer strategy
# Iterative Method
def BinarySearch(arr, n, key):
low=int(1)
high=int(n)
while(low<=high):
mid=int(low+high)/2
if(key==mid):
return int(mid)
elif(key<mid):
high=mid-1
else:
low=mid+1
return -1

print(BinarySearch({1,2,3,4,5,6,7,8,9},9,6))


# Recursive Method
def BinarySearch(arr, low, high, key):
if(low==high):
if(arr[low]==key):
return low
else:
return 0
else:
mid=int((low+high)/2)
if(arr[mid]==key):
return mid
if(key<arr[mid]):
return BinarySearch(arr,low,mid-1,key)
else:
return BinarySearch(arr,mid+1,high,key)




index = BinarySearch([1,2,3,4,5,6,7,8],0,7,2)
print(index)



Comments

Popular posts from this blog

Knowing too much is bad(in the world of OOP)

Reverse a LinkedList Algorithm

DateTime.Now in C#