what is binary search-
In binary search we compare the value with the mid value .
Let's we have to search x for this in binary search we use following steps:-
- compare x with the mid value.
- if mid value is equal to number then return .
- if value is greater than mid value then change lower limit by mid+1 .
- if value is less than mid value then change upper limit by mid-1.
Code:-
list=[]
n=int(input("Enter the number of element in the list "))
for i in range(n):
list.append(int(input()))
value=int(input("Enter the value to be searched "))
# logic for binary search
lb=0
ub=n
while(lb<=ub):
mid=(lb+ub)//2
if list[mid]==value:
print("Value is present in list ")
break
elif list[mid]>value:
ub=mid-1
elif list[mid]<value:
lb=mid+1
Output:-
Enter the number of element in the list 6
12
23
45
67
87
89
Enter the value to be searched 45
Value is present in list
Recommended Post:-
- Hackerearth Problems:-
- Very Cool numbers | Hacker earth solution
- Vowel Recognition | Hackerearth practice problem solution
- Birthday party | Hacker earth solution
- Most frequent | hacker earth problem solution
- program to find symetric difference of two sets
- cost of balloons | Hacker earth problem solution
- Chacha o chacha | hacker earth problem solution
- jadu and dna | hacker earth solution
- Bricks game | hacker earth problem
- Anti-Palindrome strings | hacker earth solution
- connected components in the graph | hacker earth data structure
- odd one out || hacker earth problem solution
- Minimum addition | Hackerearth Practice problem
- The magical mountain | Hackerearth Practice problem
- The first overtake | Hackerearth Practice problem
Hackerrank Problems:-Data structure:-- Playing With Characters | Hackerrank practice problem solution
- Sum and Difference of Two Numbers | hackerrank practice problem solution
- Functions in C | hackerrank practice problem solution
- Pointers in C | hackerrank practice problem solution
- Conditional Statements in C | Hackerrank practice problem solution
- For Loop in C | hackerrank practice problem solution
- Program to find cycle in the graph
- Implementation of singly link list
- Implementation of queue by using link list
- Algorithm of quick sort
- stack by using link list
- program to find preorder post order and inorder of the binary search tree
- Minimum weight of spanning tree
- Preorder, inorder and post order traversal of the tree
0 Comments