Copyright © Programs ++
Design by Dzignine
Wednesday, 1 February 2012

Linear Search in array

Linear search is one of the most basic techniques used while programming in C, C++ or any other programming language for that matter. It is also taught in school and college and is one of the fundamental techniques used to search in an array. Linear search is implemented by searching each element in the array with the value that is to be searched.

In this method, the user is prompted to insert the value which has to be searched and the position where the element is stored is given as output. In simple words, the user enters the value which has to be searched, the program searches the array to find that value and if the value is found then the position where the element is found is displayed.
Consider the following code snippet :
// Program to implement linear search (by value)
#include <iostream>

int main()
{
    int arr[20],n;
    int position,value,flag = 0;
    // prompts the user to enter the no of elements in the array
    std::cout<<" Enter the no of elements you want to insert (max 20) ? ";
    std::cin>>n;
    for (int i=0; i<n; i++) // loop to enter the elements in the array
    {
        std::cout<<" \n Element "<<i<<" : ";
        std::cin>>arr[i];
    }
    // asks the user to enter the value that is to be searched
    std::cout<<"\n Enter the value to find in the array : ";
    std::cin>>value;
    std::cin.ignore();
    // searches the position by checking each value in the array
    for(int i=0; i<n; i++)
    {
            if ( arr[i] == value )
            {
                 position = i;
                 flag = 1;
                 break; //breaks the loop if value is found
            }
            else
                flag = -1; // assigns -1 to flag variable if value is not found
    }
   
    if ( flag == -1 ) // displays error message if value is not found
       std::cout<<" \n Element NOT FOUND !!! ";
    else             // displays the searched value along with its position
       std::cout<<" Value "<<value<<" found at postiton : "<<position;
   
    std::cin.get();
    return 0;
} // end of main
 

Linear search using value to find position

NOTE : Since linear search involves processing the entire array, it takes considerable time and resources if the size of the array is quite large. Hence, more efficient searching techniques are used such as binary search etc.

------ Related Posts ------ 

Binary Search : http://programsplusplus.blogspot.in/2012/02/binary-search-in-array.html

0 comments:

Post a Comment

Comment Here....