#include <iostream> using namespace std; class LinearSearch { public: int search(int arr[], int n, int len) { for(int i = 0; i < len; i++) { if(arr[i] == n) return i; } return -1; } }; int main() { int arr[] = {5, 3, 6, 2, 1, 4}; int size = sizeof(arr) / sizeof(arr[0]); int n = 2;// Element to be searched. cout << "The Array elements are : "; for (int i=0; i<size; i++) cout << arr[i] << " "; cout << "\nElement to be searched : " << n << endl; LinearSearch linearSearch; int index = linearSearch.search(arr, n, size); if(index == -1) cout << "Element is not present in the array"; else cout << "The element " << n << " is present at index " << index; }
The above code is quite simple,
We will be searching the element 2,
int n = 2;// Element to be searched.
From the array,
int arr[] = {5, 3, 6, 2, 1, 4};
Of size,
int size = sizeof(arr) / sizeof(arr[0]);
Next, we pass the array and the element 2, to the search(...) method.
int index = linearSearch.search(arr, n, size);
int search(int arr[], int n, int len) { for(int i = 0; i < len; i++) { if(arr[i] == n) return i; } return -1; }
We need to search the element 2 from the below array.
So, we run a for loop. Starting from the 1st location to the end of the array.
for(int i = 0; i < len; i++) { if(arr[i] == n) return i; }
And at every step, we keep on checking if the element is present in the array or not.
if(arr[i] == n) return i;
If we find the element, we return that particular location.
return i;
But, what if we are searching for an element that is not present in the array?
Say, we are searching for number 8. Which is not present in the array.
In that case, we return -1.
return -1;
Which states the number is not found.
Finally, the returned value is stored in the index variable.
int index = linearSearch.search(arr, n, size);
And we print it using :
cout << "The element " << n << " is present at index " << index;