TheAlgorithms-C-Plus-Plus/search/Linear Search.cpp

48 lines
667 B
C++
Raw Normal View History

2019-08-21 10:10:08 +08:00
#include <iostream>
2017-12-24 01:30:49 +08:00
using namespace std;
int LinearSearch(int *array, int size, int key)
2017-12-24 01:30:49 +08:00
{
for (int i = 0; i < size; ++i)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
if (array[i] == key)
2017-12-24 01:30:49 +08:00
{
return i;
2017-12-24 01:30:49 +08:00
}
}
return -1;
}
int main()
{
int size;
2019-08-21 10:10:08 +08:00
cout << "\nEnter the size of the Array : ";
cin >> size;
2019-08-21 10:10:08 +08:00
int array[size];
2017-12-24 01:30:49 +08:00
int key;
//Input array
2019-08-21 10:10:08 +08:00
cout << "\nEnter the Array of " << size << " numbers : ";
for (int i = 0; i < size; i++)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
cin >> array[i];
2017-12-24 01:30:49 +08:00
}
2019-08-21 10:10:08 +08:00
cout << "\nEnter the number to be searched : ";
cin >> key;
int index = LinearSearch(array, size, key);
if (index != -1)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
cout << "\nNumber found at index : " << index;
2017-12-24 01:30:49 +08:00
}
else
{
2019-08-21 10:10:08 +08:00
cout << "\nNot found";
2017-12-24 01:30:49 +08:00
}
2019-08-21 10:10:08 +08:00
2017-12-24 01:30:49 +08:00
return 0;
}