Searching Algorithms: Dissection of Linear Search and Binary Search.

Searching Algorithms: Dissection of Linear Search and Binary Search.

Β·

7 min read

The word 'search' means 'to find something'. And 'algorithm' means a process of solving a problem or task step by step. So, searching algorithm is to find something through specific sequence of rules.

The interesting fact is that we constantly use algorithms in our daily life without even realizing. Let's understand through an example. Suppose you want to go to India from Bangladesh. There are several routes you can take. By road, by train and by air as well. Now the question is, if you decide to go by road then surely you will have to pay for the bus tickets and you will wait for the bus to arrive at the given time. Same goes for train and air as well. If you want to go by air, definitely you are not going to buy a bus ticket and wait for the bus, right?. You will buy a plane ticket and follow the next steps accordingly.

Here you first decided which path to take and you completed your work at each step accordingly, in simple terms this is called algorithm. In the same way, we can find something through searching algorithm. So, I think you already understand the significance of Searching Algorithm. This algorithm has two parts.

1. Linear search algorithm

2. Binary search algorithm

Before moving on to how to apply these two algorithms through programming in computer science or software engineering, let's see some examples of these two algorithms in our everyday life.

Suppose you love to read books. You have a huge book-shelf where your books are arranged randomly. Now you want to find a book called 'Head First Design Patterns' from that shelf. How will you do it? Since the books are not arranged in order and are placed in random order, you have to search by the name of each book until you find that book. This is called linear search. That is to search one by one until it is found.

But what if the books are arranged in order from A to Z? In that case, is there any need to find one by one from the beginning? Think about it. No. Because it's serialized and the first letter in the book is 'H', you'll go directly to the 'H' serial and search there. You will eliminate all serials before 'H'. This is called binary search algorithm.

But the main condition of binary search is that your elements have to be sorted from smallest to largest or largest to smallest or by name. Otherwise binary search is not possible. This arranging data in ascending or descending order is called sorting in programming. The elements must be sorted in order to apply binary search.

But the thing is since we are human, we can understand with our eyes that I have to look for 'H' in that serial and leave the rest. But the computer will not understand that. It needs instructions for each step. Only then it can complete this process. This requires some mathematical equations.

Now let's see how to implement these two algorithms in code. First let's look at linear search.

First we are taking an Array which contains some numbers. Note that the numbers are random. This means, we will perform linear search here. For ease of understanding, assume that this array is that book-shelf and the each number represents a book.

1_NPEdrLeCouhvKZG_bU6ttg.webp

Task is to find the number 145 from this Array. Just like that book. Then that should also be declared.

1_yZhdK9pPExCjJmWEEywqkg.webp

Now declare a function which accepts the Array and Target as parameters. All our work will be done inside this function.

func.webp

Since we have to search in the entire Array it's obvious that we have to run a loop on that Array which will start from the 0 index of the Array and will run till the end of that Array. Let's write the code required for this.

loop.webp

Now inside the loop we will check that if the index value of our Array is equal to our target value then we have got our desired result and return it with a message. Means, if the value of the 2nd index of the Array matches the target value, then we will return 'Data found at 2'. And since we're dealing with condition checking, we'll have to use an If block. This code is shown below.

if.webp

And if our target value does not match with any index value of the Array then we will return the message 'Data not found'. But this must be done outside the loop. Since we don't know how many times the loop will run. If the value does not match the first time the loop runs, it will return 'Data not found' instead of coming out of the loop.

return.webp

Finally, we will call the function and since this function takes Array and Target parameters, we will pass these two parameters as arguments while calling and log the function to the console to see the output.

log.webp

Desired Output: Data Found at 5

Now let's see the implementation of binary search. In the same way as before, an Array and a target value should be declared respectively.

arr.webp

But notice that this time our Array is sorted from smallest to largest. Which is the main condition of binary search that Array has to be sorted. Then as before we will declare our target value i.e. the value we want to find.

target.webp

Similarly, a function is declared which accepts the Array and Target as parameters. All our work will be done inside this function.

func.webp

Now first we need to find out the start index, end index and middle position of the Array. The formula for finding the middle position is to add the first index with last index of our Array and divide it by 2. Below is the code showing it.

mid.webp

Since our index starts from 0, to get the end index, we have to subtract 1 from the length of Array. And our middle position should never be a decimal number this is the reason we have cascaded the entire formula inside Math.floor().

Just like before we will take the help of a loop but this time we will use the while loop. In which there will be a condition that as long as the start index of the Array is less than or equal to the end index, we will continue this loop. The rest of our calculations will be done inside this loop

loop.webp

Binary search basically has 3 steps. First we will check if the middle position of our array that we have already extracted, matches our target value or not. If it matches then we will return the index as before. And if it doesn't match then we go to the next condition and see if our middle position value is less than our target value or not. If it is small then it is clear that we will not search all the values ​​before our middle position. Let's visualize the logic.

val.webp

Here our target value 90 will be compared with middle position 50. They are not equal, middle position 50 is smaller than target value 90. So now all indexes on the left side will be dropped. For this, if you add 1 to the middle of the start value, the indices on the left side will be eliminated in the next loop. And again only in that we will find out our middle position again If our second step also fails then we go to step three and see if our middle position value is greater than our target value. If it is larger then we will not search all the values ​​after our middle position.

code.webp

And if our target value does not match with any index value of the Array then we will return the message 'Data not found'. But this must be done outside the loop. Since we don't know how many times the loop will run. If the value does not match the first time the loop runs, it will return 'Data not found' instead of coming out of the loop.

Finally, we will call the function and since this function takes Array and Target parameters, we will pass these two parameters as arguments while calling and log the function to the console to see the output.

Below is a GIF of how this entire process of binary search works.

1_fQBx0_j354hJSIkmsACUYw.gif

Β