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); }
int linearSearch(int sArray[], int first, int last, int elem)
{
int i = first;
for (; i <= last && sArray[i] != elem; i++);
return i;
}