Searching algorithms are designed to locate the position of an element (if present) in a data structure.
To search for an element in a linear data structure like an array, we can use many different types of searching algorithms. Here we're gonna talk about two most important searching methods - Linear Search and Binary Search.
Now, imagine that you're in a cake shop and there are all these delicious flavours of cakes kept before you. But all you want is a butterscotch flavoured cake. What method would you choose to find that particular flavour of cake among all those cakes? That method is what we call a Searching Algorithm.
You might want to follow this method to search for it -
-> Start from one end of the line of cakes and
-> Go on checking each cake until you find the one you want. This method of searching is actually known as "Linear Search".
Now suppose that these cakes are randomly numbered. Suppose that the Butterscotch cake is labelled with a specific number, say 34. Then you can follow this method to find it-
Sort the cakes in increasing order of their numbers.
set lower limit(l) = cake with the smallest number and upper limit(u) = cake with the largest number.🤩 Our Amazing Sponsors 👇View WebsiteDigitalOcean offers a simple and reliable cloud hosting solution that enables developers to get their website or application up and running quickly.View WebsiteThe official Laravel job board. Find the best and most talented Laravel developers by posting your job on the official Laravel job board.View WebsiteSay "hi" to Zigi - your Slack-based workflow assistant, which pings you only on relevant Jira & GitHub changes, saves time on PRs, and more!
Calculate the average of l and h.
Start with the cake which has number just greater than or equal to the average. That is the middle-most cake. Let m be the number of that cake.
Now, check if the number you're searching for is greater than or less than or equal to m. If equal, then m is the answer. Else if:
-> Greater - Change l(or lower limit) to the cake number just after cake m.
-> Smaller - Change u(or upper limit) to the cake number just before cake m.
Repeat the steps from 2 to 5 again and again until you reach the cake number you're searching for.
This method is not as straightforward as the linear search one. So here's an explanatory gif to make the algorithm a bit easier for you -
I've just tried to give a brief explanation of the two search methods. I hope you liked reading this article and learned something from it. You can check out my other articles here.
Thanks for reading!