[C++] Linear search algorithm

Questions about programming languages and debugging
Post Reply
User avatar
ayu
Staff
Staff
Posts: 8109
Joined: 27 Aug 2005, 16:00
18
Contact:

[C++] Linear search algorithm

Post by ayu »

I had to translate this from Swedish (It's from my old forum), so if you find any odd grammatical errors, well, you can point it out if you want, but at least you know the reason ^^


....


In a linear search algorithm, you loop through a list of information (arrays for example), and simply stop when the information is found, or continue to the end if not.


+
Linear search is good in the way that it's easy to understand and implement. Also, the information in the list does not have to be in a specific order.

-
The negative side is that if you have a list of 1000000 objects to search through, and the object you are looking for is at the back of the list (or doesn't exist at all), then the algorithm has to go through the whole list, which will take a lot of time, and is rather inefficient.



Linear Search

Code: Select all

/*
You send the list to be searched, the size of it and the value you are looking for to the search function.
*/

int LinearSearch(int list[], int size, int value)
{
   
        /*
         The position is set to -1, because if the value does not exist,
         then we want a non-existent position to be returned.
        */

        int position = -1;
        bool found   = false;
   
        /*
        Sets the index position to 0 (the starting position)
        and loops through the array until the position reaches "size"
        or until it finds the value.
        */

        for(int i=0; i <= size && !found; ++i)
        {
                if(list[i] ==  value)
                {
                        found = true;
                        position = i;
                 }
        }

        return position;
}
"The best place to hide a tree, is in a forest"

Post Reply