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

49 lines
648 B
C++
Raw Normal View History

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