Linear search algorithm – Linear search example

Linear search algorithm is most basic search that we do in our regular life. For example while searching one of the cloth from heap of cloths, or finding key from bunch of keys. When you have random list of thing where you don’t know order of things in the collection or array then its better if you do the linear search than anything else.

e.g. you have various number plats in box from 0-9. You have to find number plate with number 7 and you can only check one plate at a time. Then its good if you start puling one and checking if it is number 7 else throw it away.

Hence by this algorithm you can solve a problem of n size in worst case scenario in O(n) time (in big O notation). As size grows the time grows by the size of problem.  Many of the common programming things use this e.g LINQ, JQuery to find particular item.

Code example of linear search algorithm:

int LinearFind(values,numberToFind)

{

for( int i =0; i < values.Length;i++)

{

if(values[i] == numberToFind)

return i;

}

return -1;

}

This function returns index of number found else -1 to suggest that number is not in collection.

 

3 thoughts on “Linear search algorithm – Linear search example

  1. Today, I went to the beachfront with my kids. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is totally off topic but I had to tell someone!

  2. This is a great governed by discuss. From time to time I personally fav that in Redit. Evidently this time period I am not confident that this is best for users. I’ll shop around and look for an additional content which will perform.

  3. Pingback: 手機保護套

Leave a Reply

Your email address will not be published. Required fields are marked *