-
Notifications
You must be signed in to change notification settings - Fork 6.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1419 from Aayushs1602/Aayushs1602-patch-1
Binary Search in python
- Loading branch information
Showing
1 changed file
with
24 additions
and
0 deletions.
There are no files selected for viewing
24 changes: 24 additions & 0 deletions
24
Program's_Contributed_By_Contributors/Python_Programs/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,24 @@ | ||
#taking input | ||
arr = list(map(str, input("enter array").split())) | ||
|
||
#element to search | ||
element = input("enter element to search") | ||
|
||
#implementing binary search | ||
left = 0 | ||
right = len(arr)-1 | ||
|
||
check = 0 | ||
|
||
while left<right: | ||
mid = (left+right)//2 | ||
|
||
if arr[mid] == element: #if element is found | ||
check = 1 | ||
break | ||
elif arr[mid] > element: # if element is less than arr[mid] | ||
right = mid - 1 | ||
else: # if element is greater than arr[mid] | ||
left = mid + 1 | ||
|
||
print("element found") if check else print("element not found") #print found if check == 1 else not found |