Trivial C, C++ Programs.

Linear Search in C++



Oh yeah, they ask us to make Linear Search TOO. This code is as simple as it gets. Sorry, but making it any simpler would make my eyes bleed. Here you go.

 
#include <iostream.h>
#include <conio.h>
 
int linearSearch(int*, int, int, int);
 
int main()
{
  int *sArray, mSize, i, elem, index;
 
  cout<<"\n Enter the maximum size of array : ";
  cin>>mSize;
 
  sArray = new int[mSize];
 
  cout<<"\n Enter the elements of the array : \n";
 
  for (i=0; i<mSize; i++)
    {
      cin>>sArray[i];
    }
 
  cout<<"\n Enter the element to be searched : ";
  cin>>elem;
 
  index = linearSearch (sArray, 0, mSize-1, elem);
 
  if (index < 0)
    {
      cout<<"\n Element not found";
    }
  else
    {
      cout<<"\n The element was found at index "<<index;
    }
 
    getch();
 
}
 
int linearSearch(int sArray[], int first, int last, int elem)
{
  int i = 0;
 
  for (i = first; i <= last; i++)
    {
      if (sArray[i] == elem)
	{
	  return i;
	}
    }
 
  return -(first + 1);
}

1 Comment to Linear Search in C++

  1. March 28, 2010 at 14:11 | Permalink

    int linearSearch(int sArray[], int first, int last, int elem)
    {
    int i = first;

    for (; i <= last && sArray[i] != elem; i++);

    return i;

    }

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">