Search Algorithms

Search Algorithms

Written by Richa Kiran on Aug 6th, 2021 Views Report Post

Table of contents

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. cakesearch.gif 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-

  1. Sort the cakes in increasing order of their numbers.

  2. set lower limit(l) = cake with the smallest number and upper limit(u) = cake with the largest number.

  3. Calculate the average of l and h.

  4. 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.

  5. 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.

  6. 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 - cakeBin.gif

Fin.

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!

Comments (0)