Linear Search Algorithm Implemented in C++

Linear Search is the simplest of searching techniques that can be implemented with a simple array and a for loop. All elements of a particular array are checked one by one to find a given key element. If the element is found, the system returns that the search was successful. Also the user will be presented with a location where the search element was found i.e. the index in the array matched. See the code below followed by the C++ source code: 



#include <iostream>

using namespace std;

int main()
{
        int MyArray[100], KeyElement, c, input_number;

        cout<< "Enter the number of elements in array\n" ;
        cin>> input_number;

        cout << "Enter " << input_number << " numbers\n" ;

        for ( c = 0 ; c < input_number ; c++ )
             cin>> MyArray[c];

        cout << "Enter the number to search\n";
        cin>> KeyElement;

        for ( c = 0 ; c < input_number ; c++ )
        {
            if ( MyArray[c] == KeyElement )
                 {
                      cout << KeyElement <<" is present at location " << c+1;
                      cout << "\n"
                      break;
                 }
        }

        if ( c == input_number )
        cout << KeyElement << " is not found in array.\n";

        return 0;
}


Download Source Code Here. Notice that the C++ Souce Code is written in Code::Blocks 12.11 IDE available for direct download Here.

Please ask your questions and list your suggestions below in the comments section.

No comments:

Post a Comment

Custom Search