-
Notifications
You must be signed in to change notification settings - Fork 17
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added binary search in searching techniques
- Loading branch information
1 parent
8a136a5
commit 72b1be1
Showing
1 changed file
with
34 additions
and
0 deletions.
There are no files selected for viewing
34 changes: 34 additions & 0 deletions
34
Python/Searching_Techniques/Binary_Search/binary_search.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
# Binary Search in python | ||
|
||
def binary(arr,low,high,key): | ||
# It will run the loop while startIndex is less than or equal to endIndex | ||
while(low<=high): | ||
mid=(low+high)//2 | ||
|
||
if(arr[mid]==key): | ||
print(arr[mid],"<- Found!!", "at index",mid) | ||
# If value of element is equal to the array at middleIndex then return that index | ||
break | ||
|
||
elif(key not in arr): | ||
print("Not found") | ||
break | ||
|
||
# If the value of key is less than value of the array at middleIndex then decrease high by mid-1 | ||
elif(arr[mid]>key): | ||
high=mid-1 | ||
|
||
else: | ||
# Else store the value of low as mid+1 | ||
low=mid+1 | ||
|
||
|
||
# Driver for the above code | ||
arr=[2,3,4,10,40] | ||
x=10 | ||
# Calling binary search funtion | ||
binary(arr,0,len(arr)-1,x) | ||
|
||
# Output | ||
# 10 <- Found!! at index 3 | ||
|