Table of contents
No headings in the article.
In the linear search algorithm, we compare each array element with the key until we find the matching key.
code for linear search
#include <iostream>
using namespace std;
// linear search
int linearSearch(int *arr, int n, int key)
{
for (int i = 0; i < n; i++)
{
if (arr[i] == key)
{
return i;
}
}
return -1;
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 0;
cin >> key;
int index = linearSearch(arr, n, key);
if (index != -1)
{
cout << "key is present at index :" << index << endl;
}
else
{
cout << "key is not present at any index :" << endl;
}
return 0;
}
Thanks for reading, have a good day! đź‘‹
Â