Lecture 12: Binary Search Explained in 1 Video [Theory + Code]

Hi everyone. How are you all? This is Love Babbar and welcome to the channel CodeHelp. Today we are going to talk about an important topic, in fact extremely important topic. It is important from the aspect of your online test as well as the questions which are being asked in the interviews. Most of your online test questions are solved with the help of this topic in a ziffy. You will be at profit once you understand it. We are talking about Binary search, those of you who don't know I will teach you very solidly about it, and those of you who know it I will teach you some additional information, I will not leave you Empty-Handed.

So, basically we are going to talk about binary search. Let's start from the beginning, Binary Search. OK, so when I talk about Search, one thing that we have already learnt about is the LINEAR search, right! We learnt about Linear Search in the second – last lecture, when we were going through the introduction video about arrays we came across a term called Linear search. What is Linear search? We had once revised it there itself . OK, so I say that I have an array like this Right! and it has elements in it 3,7,0,-2,5,9 In this way, the elements are filled in it and a Key is given to me and I have been told to find 2. OK, so to find 2 in the case of linear search, here the index i is 0, 1 ,2,3,4,5 In the starting I compared it to the 0th index, no, then I compared it with 7 (1st index), no, then with 0 (2nd index), no, then with -2 (3rd index), no, then with 5 ( 4th index),no, then with 9 ( 5th index), no.

It didn't match with anyone. None of the value is equal to 2, so 2 is absent here. Not found So, basically what I used to do in Linear search, I used to compare it with the value of each block is this the same value that I need, is this the same value that I am searching for if it is then it should be "done", and if isn't then check with the upcoming value so, in this way I used to do with the linear search, if I talk about the complexity with linear search , here we used to apply for loop from 0 to n then we check if (arr [i]==key) and if it's equal and then simply return the index, whatever index you take. And if it isn't equal then at the end of the function we would do return -1 that I didn't get the value. In this way, you would have written some codes in the case of linear search. Last video was on the topic of COMPLEXITY, so after seeing the code you might have assumed that it's simple as it's time complexity is O(n).

So what you must have felt that in the case of linear search, for an array of size n in the worst case I do n number of comparisons Now tell me, if I say that you have an array whose length is 1000, which means that it consists of total 1000 values and I am applying linear search in it, in the worst case I am doing 1000 comparisons. If you have understood the story here , then you have understood the linear search quite well. In the worst case, that is when the element is absent, I would have done 1000 comparisons and at last I will say that I didn't get the element.

Right, this was the method of linear search and we are already familiar with it, it has a good complexity , we are getting the linear time loop that is O(n). Then why do we need the Binary search, why do we need to learn it. What is the benefit here? So, this video is sponsored by RELEVEL. If you want to enter into software working and apply for prominent jobs then RELEVEL is a platform where you can get different leading companies that you can apply for like CRED ,1mg , MEESHO, Urban comapny, upGrad where you can get developer jobs.

If I talk about leaderboard, then we have amazing examples like harmonpreet singh and biswajit patra who has recently cracked the back end engineer profile in Hypto whose CTC is 28.5 lac per annum If you make your place in the leaderboard and maintain it then you will win some exciting prizes as well And how to do it? So , first you have to register for the test, you can have back end , front, analytics, business development profiles as well along with many others. you can try any of it. You will give the test, and then interviews, you have to crack it and then you will get the job offers. and you can have your first job in 15 days.

GET HIRED! OK It has many tests , you just have to book your free slot and give the test according to your convenience, crack it, give the interview and be a Hero. You can message me that I got a job. Here I am giving you a coupon code, link is in the description, you can use that and then get a job. THANK YOU! Now starts the game so when you talk about binary search it's a very beautiful topic ,ok. Let's take the example.

Ok, so there are some elements in it, so the first condition that you have to keep In mind is that binary search is applied only on the monotonic functions. binary search is applied only on monotonic functions, values should either be in increasing order or decreasing order. understood? in these two cases I will easily apply the binary search, no problem. so how is it done on monotonic functions, we will deal with that. so the binary search says, that you should follow one condition, that whatever element is present , keep it in monotonous order. element should be in monotonic functions, alright. So I said that no, i will show the function in increasing order and we will figure it out from there. so I gave the example 3, 5, 9,13, 27 so I have given this example, show me how you would apply the binary search in it. Ok , I will show a very easy example, how the binary search is being done and then you will get a little idea of it we will do it comfortably there is no hurry, ok.

So, the first condition in binary search has been fulfilled that is the monotonic function 3, 5, 9, 13, 27, alright! firstly, you have to find out the mid element. So if i do the indexing here so according to it , here it will be 0,1,2,3,4 here the mid element is 9, in the middle, after that I compare the mid- element to the key an element should be given for it to be searched right, so I told that I will search 13, like this so what did I do, now I compared the mid element to 13, if 9== 13 , answer is no, it isn't. alright, if the key was similar to the number for instance 9 == 9 as in this case I would have returned the respective index, as here it was 2.

So we have understood that if it was same then I would have returned the index, and if it isn't then what should we do. here we can see that we have two parts, one is this one and then this is the another one , now in which part should I search, how should I figure it out. I know that this is 9 and this is 13 and they are not equal, so I will go on either part. Let's look closely. we have to search 13 and the mid value is 9, and 13>9 which means that it will be on the right side of 9 because the elements that are on it's left side are smaller than 9 which means that we have to search on this side and not on this one.

Understood! so now we know that we have to search on this side, so we bring down this part This part is 13,27 this is my 3rd index and this is the 4th index, perfect! now, take out their mid element, and how is that done, simple! find the starting index and the ending index and divide them by 2 starting index is 3 and ending index is 4, divide it by 2 that is 7/2 and the final answer is 3. so which is my my mid element it's the 3rd index as the answer is 3, so I compare the key to the mid element which means I compare 13 with 13 and here and the condition here is true and then I have to return the index what is the index here, it's 3 my answer is 3 alright! so this was binary search.

You understood some of it! Let me explain once again Firstly we, found the mid element inside the array how to find the mid element, like this, we will go on normally we found the mid element, so this was our first step, alright! Second step, I compared the mid element to the KEY alright! And on this basis if it's equal then we return the index and if it isn't equal , then I decide which part I should search whether I should check the right or the left part! and then we repeat the steps. it's the same thing with the loop itself. understood! if not let's take one more example let's take one more example for you, this is an array it has 3 ,7 ,11 ,13 ,19 and 27.

Here the key is 27, I have to find 27 whether it's there or not, if it's there then nothing should be done , leave it. first , we have to find the mid value and for that let's do the indexing, here it's 0,1,2,3,4,5 starting index is 0, formula is (s+e)/2, and the ending index is 5 here it's 5/2 and the ans is 2. this means 2nd index is your mid element perfect, we have understood this much! Then we'll compare 11 with the key , it isn't equal. ok, we can write it as 11!=27 we have the first and second part, which one should I move towards to. 27>11, which means I have to go towards right, so I have written it down this part is 13, 19, 27 index is 3,4,5 alright! I'll find the mid element again, what is the mid here, (3+5)/2 that is 8/2 ans is 4 which means the 4th index, now compare it with key , 19!= 27, alright! again two parts, where should I go, 27> 19, which means i shall go to the right side understood now, I will bring it down I have written 27, the index is 5 and again find the mid,(5+5)/2, it is the start and the end itself, ans is 5 this is my mid, 27 and I'll compare it to the key that is 27 so, 27== 27, perfect! It matched! it's true, in this case we have to return the index, that is 5, and it's done perfect! so at the end we gave the ans 5 we have given the answer as 5 which is 27, in short we searched 27, we have understood this.

Alright! here you just find the mid, compare and then if it's equal you just return the index and if it's not equal then you decide the part and then repeat the process it's not much of a deal! you have understood it but still i'll give you one more example, we both have understood now I have again taken an odd example 4,8,16,22 and 34 we have to search let's say 4 our key is 4, alright! firstly we'll find the mid, what is mid, do the indexing 0,1,2,3,4 starting is 0 ending is 4 so 0+4/2 4/2 ans is 2 so our mid is 2nd index , we compared 16 to our key not equal , here 4 is less than 16 so we will move towards left part let's bring it down 4, 8 , indexing is 0,1, i found the mid by (s+e)/2 starting is 0 and ending is 1 so 0+1/2 ans is 0, which means our mid is 0th index compare 4 with the key that is 4, so 4==4 which means it is a true condition, and then return the index which is 0 which means your ans is 0.

Alright! now just assume if the key was 8 and i had reached here, then it would be 4!= 8, here8> 4, which means you are in the other part, right! Now we'll bring it down, it's 8 and it's index is 1, alright! we'll find the mid (s+e)/2 both are same so 1+1/2 that is 1, here the index is 1, which means it's the mid itself you compared it with the key, which was 8, so 8==8 which is true, and then return the index which is 1 and your ans is 1 we dealt with 3 examples, so you must have understood the binary search by now, let's take one more example but in this case the element which we have to search would be absent, let's see what happens so this is the array 5,11,13,17,19,27 do the indexing 0,1,2,3,4,5 and we have to search 25 search the key now! 25 isn't there, but you should know the basic, right! so now find out the mid it's (s+e)/2 start is 0 and is 5, (0+5)/2 and the answer is 2, alright! so now compare the mid (2nd index) with the key 13 != 2 and 25> 13 , so we have to move towards right from those two parts as 25 is greater, understood! let's go to the right one.

So i brought down the right part, it consists of 17, 19 and 27 and then indexing it 3,4,5 and now we will find the mid how to do it, that is (s+e)/2 start is 3 and end is 5 so, (3+5)/2 that is 8/2 and the ans is 4 so the mid is the 4th index and then compare 19 with the key and now 19!= 25, alright! 25>19, alright! again we have two parts, so we will move towards the right part. let's bring it down. here one element is left 27 and the index is 5, alright! you found the mid here, mid = (s+e)/2, start is 5 and end is also 5 so ans is 5, so this is your mid. Now you compare 27 with the key and 27!= 25 as 25< 27. which means you have to go towards the left side, but we don't have any part there, it doesn't exist, so we return -1 , in this way when there isn't any part left , it means that the element doesn't exist, it isn't present, not found , right! not found so this was the algorithm of binary search.

So can i code it, of course i can. i'll show you, with an example, we will take both odd and even array in account. Just keep in mind that we have to take either increasing or decreasing array. alright! so we made an array here,2,4,6,8,12,18 in the even one and 3,5,11,14,16 in the odd array. Here i have made two arrays, now i have to enter the function of binary search which runs an index, so i gave the name binary Search, firstly we have to give an array in it, and then its size, and then the key, alright! we have understood this, now i have said start, so it will always start from 0 and i said end , end will be always size -1 , alright! till here it's fine , now we will find the mid, now we will play a game with the mid, i'll show you , so don't think of it as final, for mid its (start+end)/2 there is a little mistake over here, we will see it later on.

We have done it till here, now we apply the while loop, what will be the condition here the condition of while loop was, that things are fine until s <= e, till here it's fine the moment s> e , everything becomes a mess, then we won't be able to compare, so according to the condition, until s <<e that is until the start << end till then the game goes on, after that it shouldn't.

Now here, if {arr [mid] == key that is if they match, return the index, the mid is the index itself. alright! lets move on, what might be the next case, if that is if the value is bigger then you have to go towards the right part, how we will do it, see its very simple. here the start was 0 and end was 5, if i have to move towards right then its simple, end will be the same, i have to replace the start.

So 13 is the mid value , so start will be mid +1, understood! if i had to go to the left, the start would have been the same instead the end would have been replaced. and how will it be done, by mid -1. it means for left part, its e= mid -1 and for the right part , its s= mid +1, simple! now in this case, if the key is bigger , then you have move to the right part, i'll write it here , go to right part, what you have to do is s= mid +1.

Else, what will we do apart from this? simple logic, we'll go left , simply we put end= mid -1 , till here is it clear? still something is missing , so here the start and the end as well has been updated. and now we would have to update the mid as well , right! mid = (start+end)/ 2, we get a new mid. DONE! if still nothing happens then return -1, here your code for binary search is ready. lets run it once and then i'll explain , what has happened here. here int index =Binary Search[even, 6, 12] size is 6 and now search 12 in it , what shall be the ans cout<< " Index of 12 is" << index <<< end and now you run it. here it says the index of 12 is 4, lets check it ,0,1,2,3,4, GOOD! what if i make it 18 the ans shall we 5, lets see what comes. for 18 its 5, very good! now assume that i change the search element to 20 , the ans shall be -1, very fine good! now, if we do it for odd, so i did it for odd as well.

Odd Index, go for the odd array whose size is 5, and search 8 in it and print it. index of 8 is … now i'll run it. what is the index of 8, her its 1 as well as the ans is also 1, alright! and if i had done it for 16 then the ans shall be 4 , lets see what comes! for 16 its 4, perfect! assume if i search an element which doesn't exist, like 20 then what will happen, oh here i didn't update it 20 now lets run it and see, its -1, so our code is running perfectly, alright! understood! i'll explain the code once again if you didn't understand it.

Lets understand the code once again. so in the code, its said to take start as 0 and end as n-1 n means size, and then compute the mid that is (s+e)/2, ok! Till line no.9 its this much , we haven't done anything else, you must have understood this, then until start <= end or s<= e, what does it mean that until the start is on the right and the end is on your left of the array, till then its fine, if they are at the same location its still fine but the start shouldn't surpass the end, this situation is wrong, so we have written while (s<=e) then we will do something, and what is that something, earlier we used to compare it with the mid element, so the value in array of mid is compared with key, i am talking about line no. 13, i checked if they both are equal, yes they are equal, and if they are equal the index that is here, just return it.

And we found the index and the name is mid so we returned the mid , now only two cases are left, either the key will be bigger than the element, then we will search the right part, or if its smaller , then we'll search the lesft part so line 18 says that my key is bigger, so if my key is bigger i'll go for the right part, end will be there we don't need to do anything, so i only have to replace the s which means i have to update the s and the location is one place in front of the mid, so s is now mid +1, alright! or else, that is the condition where the key is less than arr of mid–in this condition if your key is smaller than arr of mid, you know that you have to go for the left part so what you have to do ,if we see here, that the key is smaller than arr of mid then you have to search in the left part, simple, s wil be the same only the end will be changed by end = mid -1 same thing is here end = mid -1 , alright! we have understood all the three conditions now, in equal condition return the index, in bigger condition go to the right part and in the smaller condition go to the left part after that the value of start and end has been updated, new value is there, either of the two must have been updated , so my mid depends on both of them that is start+end /2 , so one of them has been updated now which one? whichever it is i have to update the mid according to that, Now the start and end have been updated so i have to update my mid as well, so in this way i have updated the mid, perfect! now i told you there is one mistake in it, we have to find it, now we have to check it directly, we have already done it with four examples, we have walkthrough the code with two examples we have applied the code on both even and odd cases, alright! now we might do a mistake, in line no.

9 and 25 we have written that mid= start +end/2, logic wise its fine, no problem is there, we have to do it here. but here we might do a clever mistake , i know that the value of my int is 2^31 -1, assume that your start is 2^31 -1 and your end is also 2^31 -1 , assume it, both are large, so when you add or try to add these values a value appears which is out of the range of int, understood! when you add it , such a value appeared which is not in the range of int, you cannot put it in int, do you understand it? here the things get messy, and you will get stuck in the test, so you will have to be clever here, so after adding them we will get a value which is out of the range of int, so we have to be clever here so if i write the same formula in this way assume it, now the formula is mid = start+end /2, so we will cleverly separate this, so it will be s +( e-s/2), will it be fine, i can subtract atleast, i can subtract two bigger values after subtracting it will always come in the range of integer, right, so do you understand this! here we have played the game very well start and end are the indexes so they will always be positive so don't play the negative and negative becomes positive that game here s and e are indexes so ,1,2,3,4 they are all positive, right , so if i solve it here (s+e)/2- s/2 , s and -s/2 became s/2 and + e/2 = (s+e)/2 .

Oh , so this the clever thing here, i can careful from that error through this large integers will sum up and give us problems so instead i can apply this formula we call it cleverness, ok! so lets try changing it here, so what does this formula say start +( end- start )/2, perfect! same will be kept in line no, 25 as well here also it is done, oh oh, done! lets run it, here so in both the cases our ans is -1 as the 20 in the array doesn't exist.

Lets search 6 once again in the even one and 14 in the odd one. lets go! for 6 ans shall be 2 and for 14 it should be 3, ok , so we have to update here, 6 and 14 lets run it now. the ans for 6 is 2 and for 14 its 3, here our code is terrific ,exciting! lets see the code once again its a wonderful topic , there shouldn't be any doubt , we saw starting and the ending index and then found the mid value by start +end /2, ok, we have modified it in this way so our integer doesn't overflow then i said that until start<= end , you can run the loop, if the mid value matches the key value, then return it if your key is bigger than mid value go to the right an there start is mid +1 otherwise go to the left part, and end is -1 , now you will reach on line no.

24, it means either your start must have been updated or the end, either one is updated. so if either of them is updated then we have to update the mid, as it is derived from start and end, right! so we have updated the mid by start+ end/ 2 or you applied your cleverness in this way you have searched your binary, so if your value is same then it must have been returned, and if you came out on line no. 27, it means your value is absent from the array so simply return -1, its not present, not found done, in this way you have written the code for binary search. why? what is the benefit? alright! we have understood how the code works by traverse. how the example is running and what is the benefit? see, what did i tell you n the beginning , that in the case of linear search if I have an array of 1000 values. so what do I have to do in the worst case? 1000 comparisons and if I do this in the binary search, I have a sorted array of 1000 values , what do I have to do, firstly the size of my array is 1000.

Right! then I will find the mid in it and go towards either left or the right part, it would straightly be half. so , now If I go to either the left or the right part , the size will be 500 on either side. and then if I go further , the size will be 250. If I go further again It will be of 125. further on its 62 alright! further on its 31, further on its 15, further on again its of 7, and then its 3 and then its 1 and then after that its 0, lets count it once. 1,2,3,4,5,6,7,8,9,10 we don't have to count here, so we have done a total of 10 comparisons In 10 comparisons we found out If the value is present or not.

So, see here what is the difference? you had to do 1000 comparisons in case of linear search, here the complexity was O(n). but in case of binary search , you only had to do 10 comparisons, since the size of the array is same that is we have 1000 values. there is a huge difference between 10 comparisons and 1000 comparisons and what is the complexity of binary search O(log n) and how is it applied? I will tell you right so have we understood , what benefit we are having by the usage of binary search? In linear search you have to do the whole 1000 comparisons but in binary search we are playing the game with the complexity of O(log n). In the length of 1000 , you are doing 10 comparisons in the worst case.

Wonderful! wonderful! Alright! How did we come across log n? In the beginning , the size of our array was N, then you chose either of the left or right part to search on, assume we went on the right part, so what is its size now N/2. further down, assume we went for the left part this time, what is its size now N/4, its getting halved every time, and then further on we moved towards left side, its N/8 now, and taking it further suppose the size is now N/2^k, what is happening here? here its N/2^0, here its N/2^1, N/2^2 ,N/2^3, right! In this way you are going further on. so here I saw a pattern , so I said that at one place it will end where only singe element will be left, and I said that the power of N ends in 2k I don't know where it will end ,so I have to assign a variable.

Right! the power of n is 2k, so here at this length your alterations end and its equal to, what is its length ,1, right! so N is equal to 2 to the power k, so cam I say that k = log N. done! so in this way you took out the complexity. In the case of binary search, the time complexity to search an element is log N O(log N), the amount here is log N , perfect! we have learnt what is binary search, in which condition we can apply it , we tried to run it in four examples, we coded it , we tried to run it again after coding we cleverly filled the mid in the code, and then complexity….. we had comparison between binary and linear search, that why is there a benefit in binary search and how? then we understood how the complexity was log N, alright! It is a beautiful concept, we have a lot of questions , a lot , we have pretty good applications based on binary search, If i count then there are a lot of them find the Lower Bound , find the Upper Bound, you can use them to find number of occurence , alright! you found the number of occurence and then you find out the bi pivot element, search in rotated array, and then you can reduce the search phase and find the answer, just like you do in COW questions Just like you do in ROTI questions, PARATA questions and you even have BOOK allocation, very pretty questions are left here, now we have understood the concept of binary search perfectly! what next? we will be doing many questions based on binary search.

It will be an amazing experience. alright! Run and come to the next lecture and don't tell anyone! we are going to do a lot of questions. I guarantee you it will be fun and amazing! It was fun this time right! It was a small lecture! we'll meet in the next video, comment down how did you feel about this , so that its fun for me, what is the time right now? Its 3:56 am in the dawn which means its almost 4 am in the morning! I am shooting currently, you must have seen three shoots from today as I have made the previous videos in the same shirt.

I am trying to give to very good content quickly and do comment down, like or dislike this video and comment down as well, just do something and that's it in this video I'll meet you in the next video with a lot of questions , till then bye, bye. WORK HARD! OK!.