Remember Binary sort function will be performed on the sorted list, so before executed def binarySeach(list, n): just type list.sort() your program will run correctly..
Great videos sir ! Only I had to point out one correction , I think when we relocate the lowerBound or UpperBound , it should be lowerBound=mid+1 and upperBound=mid-1 . You've mentioned it in later part though . For anyone having doubt with the initial part of video , hope this comment helps :p
# in binary search the values of an array must be sorted """step 1 - set the lowerBound and upperBound step 2 - find a min index i.e lowerBound + upperBound / 2 step 3 - now we have to check that the mid value is same or not with the value we are seaching for step 4 - next change your lowerBound or upperBound 4.1 - the value we are searching for is smaller or bigger than the mid value 4.1.1 - if your value is smaller change the upperBound to midindex 4.1.2 - if your value is bigger change the lowerBound to midindex step 5 - again find a mid value repeat step 4 """ pos = -1 def search(arr,n): lB = 0 uB = len(arr)-1 while lB
I want to express my heartfelt gratitude for all the effort you put into simplifying the topics. Your presence and the way you explain things in the videos bring us joy and radiate positive energy. I hope you continue in this way, and I wish you all the best in everything you do.
Hi Navin, Thank you for these amazing videos. However in this algorithm, the last element is not found. Upper bound must be len(list) and not len(list) -1 . Another issue was that elements greater than the last value, i.e. elements not present in list and > last list value were not coming being found. This was cause the Lower bound value must be changed to "Mid + 1" instead of Mid. Thank you once again for these tutorials.
The upper bound must be len(list)-1 because the index for the last value of the list is one less than the length of the list because computers start counting from 0. The length of the list itself is an index that does not exist in the list.
sir can you make it ? Create a random list of numbers between 0 and 100 with a difference of 2 between each number. Ask the user for a number between 0 and 100 to check whether their number is on the list. The program should work like this. The program will half the list of numbers and see whether the user’s number matches the middle element in the list. If they do not match, the program will check which half the number lies in, and eliminate the other half. The search then continues on the remaining half, again checking whether the middle element in that half is equal to the user’s number. This process keeps on going until the program finds the users number, or until the size of the subarray is 0, which means the user’s number isn’t on the list.
List = int(input('enter list:')) n =int(input('enter no to be searched:')) For I in list: If i ==n : Print ('found') else: Print ('not found') Break Print ('thank you')
If the search value is smaller than list[mid] then change upper bound and (mid - 1) becomes new upper bound value. If the search value is bigger than list[mid] then change lower bound and (mid + 1) becomes new lower bound value.
I cannot understand why you have to add and subtract in the last part of the video? If the value is not found using the algorithm then why do we need to add or reduce to mid?
@@sattvaggrawal1022 Well i think that's bcz of while loop u have to increment by 1 when the mid is small than search value and decrement the value by 1 when mid is greater than search value....
@@gauravbisht9622 one of the logic can also be that we already checked the mid and it doesnt make sense to recheck it thats why we take mid+1 for l and as we move to the left in case of U so u = mid-1
In order to exit the while loop and return false. If mid has reached to the last index, l is still equal to u. And we have while condition while l u (exit the while loop and execute FALSE)
Excellent tutorial for learning, Thanks sir. some minor corrections are u= len(list) there is no need -1 and u = mid there is no need +1... Rest of code is superb .
hey Naveen, can you make this video again. Since you change the concept at the end of video for changing lower and upper, I think whole algorithm that you taught at starting will change. So please correct that algorithm.
One of biggest problem is you never zoom while writing code you should understand ... Becoz visibility is must for learners.. People appreciate by way you present it... Any ways ...nothing can change now
If you know the element you're looking for exsists in the list, and you just want to find the index for it. Is there any benefit to binary searching, or can you simply .index()? For example, I have a list of dates in the format '2020-03-01' and I want to find the index of the current days date. Is binnary searching more time efficient? Thanks
Using for loop: list=[3,4,5,6,7,8,9,70] n=9 pos=0 def search(list,n): l=0 u=len(list)-1 for i in list: mid=(l+u)//2 if list[mid]==n: globals()['pos']=mid return True else: if n>list[mid]: l=mid else: u=mid return False if search(list,n): print('found at',pos) else: print('not found')
Tried Using for Loop def search(list, x): l = 0 u = len(list) for l in range(u): mid = (l + u)//2 if list[mid] == x: return mid else: if list[mid] < x: l = mid + 1 else: u = mid - 1 return -1 list = [1,4,5,7,9,11,12,34] x = 12 result = search(list, x) if result != -1: print("Number found at ", result) else: print("Number not found")
Navin, I love your videos. I had just one question in this video and also in bubble sort and linear search videos. What if you have a list of some values which appear more than once. Also will this procedure ignore any string values inside the list or do we have to implement an exception handling ourselves?
a simple way to get the last and the first value guys. def binary(arr,k): i=0 u=len(arr)-1 if arr[u]==k: globals()["p"]=u return True for x in range(len(arr)-1): mid=(u+i)//2 if arr[mid]==k: globals()['p']=mid return True else: if arr[mid]
Hi Navin, as you have told in above video that if the search number is greater than the mid value then we will shift the lower to the mid but as i know we will always do the mid+1 for shifting lower.. i got confused that which one is correct.
The upper bound should be changed to u=mid-1 in the else part of else in while loop. Then this will be correct. Since we need to decrease the upper bound to mid -1 when n is < than mid.
Very Nicely explained bro, thanks a lot, u made it very easy to understand, if u dont explain in the beginning if directly start code then i supposed not get it.
One question.. list = [1, 3, 5, 7, 9] n = 9 How is this algorithm searching this? Because this is infinit loop here. Don't you think your u should be lenghth of the list instead of minus 1? u = len(list) def binarySearch(hey, need): heyLen = len(hey) if heyLen
Thank you Navin sir for the explanation but I have tried to implement this code which you have shown it will not give correct results on boundary values logic of assigning mid value should be change like this if list[mid] < n: l = mid + 1 else: u = mid - 1
Sir this code is unable to find the position of 0th element i.e it is printing that the no. 4 according to your program which is at 0th position in list is" Not found". So.,please suggest some changes.
hi Navin sir, Thank you for these amazing videos their is one minor mistake so the correct solution of binary search is : pos = -1 def search(list, key): l = 0 h = len(list)-1 for i in range(len(list)): mid = (l + h) // 2 if list[mid] == key: globals()['pos'] = mid return True else: if list[mid] < key: l = mid + 1 else: h = mid - 1 return False list = [3, 6, 8, 12, 14, 17, 25, 29, 31, 36, 42, 47, 53, 55, 62] key = 62 if search(list, key): print("Element founded at the position ", pos) else: print("Element is not found") o/p:Element founded at the position 14 and pos = -1 def search(list, key): l = 0 h = len(list)-1 for i in range(len(list)): mid = (l + h) // 2 if list[mid] == key: globals()['pos'] = mid return True else: if list[mid] < key: l = mid + 1 else: h = mid - 1 return False list = [3, 6, 8, 12, 14, 17, 25, 29, 31, 36, 42, 47, 53, 55, 62] key = 1 if search(list, key): print("Element founded at the position ", pos) else: print("Element is not found") o/p: Element is not found and def search(list, key): l = 0 h = len(list)-1 for i in range(len(list)): mid = (l + h) // 2 if list[mid] == key: globals()['pos'] = mid return True else: if list[mid] < key: l = mid + 1 else: h = mid - 1 return False list = [3, 6, 8, 12, 14, 17, 25, 29, 31, 36, 42, 47, 53, 55, 62] key = 6666 if search(list, key): print("Element founded at the position ", pos) else: print("Element is not found") o/p:Element is not found
@@sanyamgarg5547 Last modification logic : If we concluded that 'midvalue' is not equal to 'n' , then using midvalue index for either lower bound or upper bound is of no use, hence we need to either look at decremented position i.e midvalueIndex-1 (incase of n < midvalue) or incremented position i.e midvalueIndex+1(incase of n>midvalue)
Binary Search using for loop: pos=-1 def search(x, n): l=0 u=len(x)-1 for mid in x: mid=(l+u)//2 if x[mid]==n: globals()['pos']=mid return True else: if x[mid]
sir binary search mei upper bound len(list) hoga tabhi ager hum 99 search krenge toh humee uski position pata chelegi ager mere concept mei koi mistake ho toh please bataiyega
Great explation! But at the part when you run it and says at pos 5 dont you start counting from 0 when indexing? Because if you start at 0 and count to 5 you get 99 not 45.
@@fashionobsession6793 idk if yall still need it but he left the code as print("Found at", pos+1) so its counting starting from 1 instead,, theres an explanation for why he added 1 in his linear search video !!
Take every thing from the user:) print("BINARY SEARCH:") arr1 = [] n = int(input("size of the array:")) for i in range(n): x = int(input("enter the input into the array:")) arr1.append(x) c = sorted(arr1) print(c) pos = -1 m = int(input("searching element in the array:")) def Binarysearch(c, m): l = 0 #lower bound u = len(c) - 1 #upper bound for k in range(u): mid = (l+u)//2 if c[mid] == m: globals()['pos'] = mid return True else: if c[mid] < m: l = mid+1 else: u = mid-1 return False if Binarysearch(c, m): print("Found here:", pos+1) else: print("NotFound")
But how we can implement this in string suppose if we have a list of strings and we r also searching for a string so will it work with strings as well.
it is producing infinite loop with a number not found in list. I guess with this logic it will never go to the last position. Should we keep one more check .. if the item is last element or grater than last .. before entering into the loop??.
Sir with this logic when i searched for the last element of the list , it was not giving me result and cpu was running high. i found u= len(list)-1 needs to be changed u =len(lis) ❤u sir
Remember Binary sort function will be performed on the sorted list, so before executed def binarySeach(list, n): just type list.sort()
your program will run correctly..
bro where to type
@@arkamiqbal3221 u can put below the list
This is the most imp step which everyone forgets including me😅
TQ bro
u will not get the actual position of the element if you apply list.sort(). you only find element is present or not
Great videos sir ! Only I had to point out one correction , I think when we relocate the lowerBound or UpperBound , it should be lowerBound=mid+1 and upperBound=mid-1 .
You've mentioned it in later part though . For anyone having doubt with the initial part of video , hope this comment helps :p
mam, why we have to relocate ?
and why we are using pos = -1
it's too confusing.
[2,4,3,2,5,6,7,8] plz use this list we will get an error. if you change lower bound= mid-1 then it works
@@vigneshm9411 this list is not sorted
Exactly. Since the while loop condition is lo
I did modifications but i couldn't any output
The best video in this python series. : -)
# in binary search the values of an array must be sorted
"""step 1 - set the lowerBound and upperBound
step 2 - find a min index i.e lowerBound + upperBound / 2
step 3 - now we have to check that the mid value is same or not with the value we are seaching for
step 4 - next change your lowerBound or upperBound
4.1 - the value we are searching for is smaller or bigger than the mid value
4.1.1 - if your value is smaller change the upperBound to midindex
4.1.2 - if your value is bigger change the lowerBound to midindex
step 5 - again find a mid value
repeat step 4 """
pos = -1
def search(arr,n):
lB = 0
uB = len(arr)-1
while lB
Is this working.. when I run In each time I got not found
This is code not working broo
Thank you its working for me!
just change the numbers of the list @@Aswini.
Naveen, I haven't found even native english speakers to explain as intuively as you do in this video. Thanks a lot for what you do.
This is guy is among the legends of programming that have made alot of impacts in our society.
Finally I understood after your video. Too good 👍
Play in 0.75 speed - you're welcome 😁
❤❤❤❤ Thanks.......helped alot....man was fast and was making sense
Your videos are far better than others
you are such a good teacher ...
We are the same
I want to express my heartfelt gratitude for all the effort you put into simplifying the topics. Your presence and the way you explain things in the videos bring us joy and radiate positive energy. I hope you continue in this way, and I wish you all the best in everything you do.
Excellent. I have been revising python concepts last 2 days by watching your videos and learned many new concepts.
A great video
Something that helped me with my homework, thought it will take an entire day
Hi Navin sir, my doubt is, the code runs fine for any index position search if we do u = len(list) OR u = len(list) - 1. Why is that?
So great explanation. 10/10
Taktuk Taktuk
Thanks navin for
You videos are teaching me a lot
The code doesn't work when you try to search the last element of the list.
the corrections are:
if list[mid] < n:
l = mid+1
else:
u= mid-1
How is it
Better try
l = 0
u = len(list)
@Akshay Thanks, it is working.
he already mentioned at the end
the shifting of lower and upper bound is so easy to understand, and here I was, trying to slice the list a bunch of times...
Make sure :
elif a[mid]
the best explanation on binary search
You are the best❤❤❤❤❤
Hi Navin, Thank you for these amazing videos.
However in this algorithm, the last element is not found. Upper bound must be len(list) and not len(list) -1 .
Another issue was that elements greater than the last value, i.e. elements not present in list and > last list value were not coming being found. This was cause the Lower bound value must be changed to "Mid + 1" instead of Mid.
Thank you once again for these tutorials.
Exactly my thoughts. Lower = mid +1 or upper = mid - 1, depending on the condition.
Yes you are right
Thank you sir for mentioning this
The upper bound must be len(list)-1 because the index for the last value of the list is one less than the length of the list because computers start counting from 0. The length of the list itself is an index that does not exist in the list.
@@arakurd6351 True, this comment made me confused lol
Sir it's a request plz unload video on Python regularly
yup
Upload*😂
1:27 list explanation
4:53 implementation
sir can you make it ?
Create a random list of numbers between 0 and 100 with a difference of 2 between
each number. Ask the user for a number between 0 and 100 to check whether their
number is on the list. The program should work like this. The program will half the list of
numbers and see whether the user’s number matches the middle element in the list. If
they do not match, the program will check which half the number lies in, and eliminate
the other half. The search then continues on the remaining half, again checking whether
the middle element in that half is equal to the user’s number. This process keeps on
going until the program finds the users number, or until the size of the subarray is 0,
which means the user’s number isn’t on the list.
List = int(input('enter list:'))
n =int(input('enter no to be searched:'))
For I in list:
If i ==n :
Print ('found')
else:
Print ('not found')
Break
Print ('thank you')
But its time complexity is O(n)
If the search value is smaller than list[mid] then change upper bound and (mid - 1) becomes new upper bound value.
If the search value is bigger than list[mid] then change lower bound and (mid + 1) becomes new lower bound value.
sir,why we have to relocate ?
and why we are using pos = -1
it's too confusing.
Correct logic should be like this to assign new mid values
if list[mid] < n:
l = mid + 1
else:
u = mid - 1
@@techwithsourabh7508 i did modifications but i did not get any output
I cannot understand why you have to add and subtract in the last part of the video? If the value is not found using the algorithm then why do we need to add or reduce to mid?
Anyone pls reply I am also confused there
@@sattvaggrawal1022 Well i think that's bcz of while loop u have to increment by 1 when the mid is small than search value and decrement the value by 1 when mid is greater than search value....
@@gauravbisht9622 one of the logic can also be that we already checked the mid and it doesnt make sense to recheck it thats why we take mid+1 for l and as we move to the left in case of U so u = mid-1
## in this case you don't have to add
pos=0
def search(li,n):
l=0
u=len(li)-1
while l
In order to exit the while loop and return false.
If mid has reached to the last index, l is still equal to u. And we have while condition while l u (exit the while loop and execute FALSE)
Excellent tutorial for learning, Thanks sir. some minor corrections are u= len(list) there is no need -1 and u = mid there is no need +1... Rest of code is superb .
u=mid -1 is necessary or you won't get Not Found
@@anandbhojane8156 > But, why?
bro naveen reddy - your explanation superb..!!
Nice topics u r now discussing..
hey Naveen, can you make this video again. Since you change the concept at the end of video for changing lower and upper, I think whole algorithm that you taught at starting will change.
So please correct that algorithm.
Hi,
Since the middle element !=n so it doesn't make sense to make it lower or upper, so lower is increased and upper is decreased by 1.
can u explain plz?
One of biggest problem is you never zoom while writing code you should understand ... Becoz visibility is must for learners.. People appreciate by way you present it... Any ways ...nothing can change now
You helped me alottttttt!!!!❤️❤️❤️
Thank you so much dude ✨❣️ ! Your teaching is tons better than my professor
Hi Chechi 😂😅
@@santhosh4664 😂😂hey you !!
Cool! Liked before watching!
using for loop
pos=0
def search(list,n):
l=0
u=len(list)-1
for i in range(u):
if l
Navin, your thought process makes so much sense to me. Thanks for sharing these videos!
Thank you so much for this tutorial.
def binary_search(nums, num):
begin_index = 0
end_index = len(nums) - 1
while begin_index mid_point_value
begin_index = mid_point + 1
return None
nums = [2,4,5,6,7,8,9,10]
num = 6
print(binary_search(nums, num))
God bless you my nigga
If you know the element you're looking for exsists in the list, and you just want to find the index for it. Is there any benefit to binary searching, or can you simply .index()? For example, I have a list of dates in the format '2020-03-01' and I want to find the index of the current days date. Is binnary searching more time efficient? Thanks
Using for loop:
list=[3,4,5,6,7,8,9,70]
n=9
pos=0
def search(list,n):
l=0
u=len(list)-1
for i in list:
mid=(l+u)//2
if list[mid]==n:
globals()['pos']=mid
return True
else:
if n>list[mid]:
l=mid
else:
u=mid
return False
if search(list,n):
print('found at',pos)
else:
print('not found')
Another way to do Binary Search :
def binary_search(sequence, item):
begin_index = 0
end_index = len(sequence)- 1
while begin_index
I really appreciate this video. Thanks a lot
got = -1
def search(nums, n):
l = 0
u = len(nums) - 1
for x in range(len(nums)):
mid = (l + u) // 2
if nums[mid] == n:
globals()['got'] = mid+1
return True
else:
if nums[mid] < n:
l = mid + 1
else:
u = mid - 1
return False
ls = [9, 12, 23, 87,89,102,140]
num = 89
if search(ls, num):
print("found", got)
else:
print("not found")
pos = -1
def search(list_a,n):
l = 0
u = len(list_a)-1
while l
good explanation. one thing pl little bit slow. This is like after a tututorial u r going to catch a train.
Tried Using for Loop
def search(list, x):
l = 0
u = len(list)
for l in range(u):
mid = (l + u)//2
if list[mid] == x:
return mid
else:
if list[mid] < x:
l = mid + 1
else:
u = mid - 1
return -1
list = [1,4,5,7,9,11,12,34]
x = 12
result = search(list, x)
if result != -1:
print("Number found at ", result)
else:
print("Number not found")
Santosh Raj thanks
Santosh Raj use for I in range in place of l, otherwise it doesn’t find 1st no in the list... as l increments each time
Sir please do video on threads where 2 threads work together and share data
def binary(arr, key):
return binarySearch(arr, key, 0, len(arr))
def binarySearch(arr, key, left, right):
if leftkey:
return binarySearch(arr, key, left, middle-1)
else:
return binarySearch(arr, key, middle+1, right)
else:
return "Not found"
arr = array([2,3,5,1,2,6])
arr = sort(arr)
print(binary(arr, 1))
Navin, I love your videos. I had just one question in this video and also in bubble sort and linear search videos. What if you have a list of some values which appear more than once. Also will this procedure ignore any string values inside the list or do we have to implement an exception handling ourselves?
Thanks, this helped a lot.
Can I ask you why are you learning programming.....? Just curious..
@@anuragrai8128 I like creating things for people to use, simply.
a simple way to get the last and the first value guys.
def binary(arr,k):
i=0
u=len(arr)-1
if arr[u]==k:
globals()["p"]=u
return True
for x in range(len(arr)-1):
mid=(u+i)//2
if arr[mid]==k:
globals()['p']=mid
return True
else:
if arr[mid]
Mama nee videos keka, ikkada dhaka ochina ante ardham chesko.
ur videos make so simple learning python. thanks.
Hi Navin, as you have told in above video that if the search number is greater than the mid value then we will shift the lower to the mid but as i know we will always do the mid+1 for shifting lower.. i got confused that which one is correct.
both are correct(mid+1,mid) but if we take mid it makes more iterations than mid+1
Hi Naveen...!
For binary search there is one condition. You have to mention that.
"Elements should be sorted"
he says a lot of time
sir thanks for making such amazing videos ...................big fan sir
The upper bound should be changed to u=mid-1 in the else part of else in while loop. Then this will be correct.
Since we need to decrease the upper bound to mid -1 when n is < than mid.
Thank you so much. This really helped me out.
I am unable to fetch some values of my list though they are in the list but at run time it shows "not found" ?
Great video sir ❤
sir their is one minor mistake in 'u=len(list)-1' so it must be "u=len(list)"
@icketypickety ROHIT is right!!! try to use the same program searching for 99 and yo'll run into an infinite loop....
@@MartialWafo I searched for the same no error, no infinite loop ,, its the right concept. send ur code if not working I will try
Very Nicely explained bro, thanks a lot, u made it very easy to understand, if u dont explain in the beginning if directly start code then i supposed not get it.
This video is very good. Thanks
thank you for lesson you are really the best teacher
One question..
list = [1, 3, 5, 7, 9]
n = 9
How is this algorithm searching this?
Because this is infinit loop here.
Don't you think your u should be lenghth of the list instead of minus 1?
u = len(list)
def binarySearch(hey, need):
heyLen = len(hey)
if heyLen
@telusko. Anything on above comment?
His habit of using a semicolon😂
java bro java
@@anirudhmalik5107 true
@@kabirchawla4325 I know 😌
Yo this series is just amazing
Sir it not give last value of list is our required search. Plz answer sir
I think it is better to use l=mid+1 and u=mid-1 since we know mid value is not the one we are searching for. so it can be avoided
Sir how can we do this with the help of the method of recursion ?
def binarysearchrec(arr,low,high,n):
if low x:
return binarysearchrec(arr,low,mid,n)
else:
return binarysearchrec(arr,mid,high,n)
else:
return -1
def binarysearchiter(arr,n):
low = 0
high = len(arr) - 1
mid = 0
while low
Thank you Navin sir for the explanation but I have tried to implement this code which you have shown it will not give correct results on boundary values logic of assigning mid value should be change like this
if list[mid] < n:
l = mid + 1
else:
u = mid - 1
why
Sir this code is unable to find the position of 0th element i.e it is printing that the no. 4 according to your program which is at 0th position in list is" Not found". So.,please suggest some changes.
Add another if statement i.e
If list[0] == n:
print("found at",0)
return True
Sir at last why are we adding +1 and -1 for the mid .
My doubt it worked perfectly before adding and subtracting 1 to that
Hello Sai, try running without +1 and -1 and pass the value of n as the last or the first element of array. You will get your answer.
hi Navin sir, Thank you for these amazing videos their is one minor mistake
so the correct solution of binary search is :
pos = -1
def search(list, key):
l = 0
h = len(list)-1
for i in range(len(list)):
mid = (l + h) // 2
if list[mid] == key:
globals()['pos'] = mid
return True
else:
if list[mid] < key:
l = mid + 1
else:
h = mid - 1
return False
list = [3, 6, 8, 12, 14, 17, 25, 29, 31, 36, 42, 47, 53, 55, 62]
key = 62
if search(list, key):
print("Element founded at the position ", pos)
else:
print("Element is not found")
o/p:Element founded at the position 14
and
pos = -1
def search(list, key):
l = 0
h = len(list)-1
for i in range(len(list)):
mid = (l + h) // 2
if list[mid] == key:
globals()['pos'] = mid
return True
else:
if list[mid] < key:
l = mid + 1
else:
h = mid - 1
return False
list = [3, 6, 8, 12, 14, 17, 25, 29, 31, 36, 42, 47, 53, 55, 62]
key = 1
if search(list, key):
print("Element founded at the position ", pos)
else:
print("Element is not found")
o/p: Element is not found
and
def search(list, key):
l = 0
h = len(list)-1
for i in range(len(list)):
mid = (l + h) // 2
if list[mid] == key:
globals()['pos'] = mid
return True
else:
if list[mid] < key:
l = mid + 1
else:
h = mid - 1
return False
list = [3, 6, 8, 12, 14, 17, 25, 29, 31, 36, 42, 47, 53, 55, 62]
key = 6666
if search(list, key):
print("Element founded at the position ", pos)
else:
print("Element is not found")
o/p:Element is not found
why have we done mid+1 and mid-1 please tell
@@sanyamgarg5547 Last modification logic : If we concluded that 'midvalue' is not equal to 'n' , then using midvalue index for either lower bound or upper bound is of no use, hence we need to either look at decremented position i.e midvalueIndex-1 (incase of n < midvalue) or incremented position i.e midvalueIndex+1(incase of n>midvalue)
thanks for explaining the logic here
why you are mentioning return true and return false, can you please elaborate this
This is just amazing...
Sir your all video list is good and well arranged but please try to make background font big so that we can see them easily in our Android phones
thxx very much--------very much fun learning python from you
position (pos=0) can be declared like this also because The In search function we are modifing the pos at iteration
OSM WRK 👌👌
Binary Search using for loop:
pos=-1
def search(x, n):
l=0
u=len(x)-1
for mid in x:
mid=(l+u)//2
if x[mid]==n:
globals()['pos']=mid
return True
else:
if x[mid]
we need to assign value from list for n
Elegant explanation...
I like this active and simple way of teaching,,, anyways thank you sir,,,
sir binary search mei upper bound len(list) hoga tabhi ager hum 99 search krenge toh humee uski position pata chelegi ager mere concept mei koi mistake ho toh please bataiyega
If user doesn't enter in sorting order. Then we need to sort the values right?
To correct the issues:
list= [4,8,100,150,177,200,201,205,300,350,400]
n= 400
poss = 0
def search(list,n):
low = 0
upper = len(list)
while low
Excellent sir
Great explation! But at the part when you run it and says at pos 5 dont you start counting from 0 when indexing? Because if you start at 0 and count to 5 you get 99 not 45.
Same question also raised by me
@@fashionobsession6793 idk if yall still need it but he left the code as print("Found at", pos+1) so its counting starting from 1 instead,, theres an explanation for why he added 1 in his linear search video !!
I want to give 1000000 likes on each video.
Take every thing from the user:)
print("BINARY SEARCH:")
arr1 = []
n = int(input("size of the array:"))
for i in range(n):
x = int(input("enter the input into the array:"))
arr1.append(x)
c = sorted(arr1)
print(c)
pos = -1
m = int(input("searching element in the array:"))
def Binarysearch(c, m):
l = 0 #lower bound
u = len(c) - 1 #upper bound
for k in range(u):
mid = (l+u)//2
if c[mid] == m:
globals()['pos'] = mid
return True
else:
if c[mid] < m:
l = mid+1
else:
u = mid-1
return False
if Binarysearch(c, m):
print("Found here:", pos+1)
else:
print("NotFound")
mr genius.thankyou
can you explain me why l=mid+1
and u=mid-1
no need for explanation i got it bro.any way thank u
if we pass a sorted list to the function like(if sorted(List):) why it is not searching for the element?
can you upload video on stack, queue, binary tree.
But how we can implement this in string suppose if we have a list of strings and we r also searching for a string so will it work with strings as well.
it is producing infinite loop with a number not found in list. I guess with this logic it will never go to the last position. Should we keep one more check .. if the item is last element or grater than last .. before entering into the loop??.
Sir with this logic when i searched for the last element of the list , it was not giving me result and cpu was running high.
i found u= len(list)-1 needs to be changed u =len(lis)
❤u sir
Yes.,
correct
Wait, does the return statement end the while loop? Because the condition raised at while always has to be true :/
What would one's do if you should to find couple numbers in list?
Thank You !
Sir can u tell me what should I do for my Ty project???
Sir what..?? if that searching element is less then the first value...
Not found