Rectified Linear Search

Previous programme was returning key instead of index. Fixed it.
Changed size of array from 10 to variable sized array.
This commit is contained in:
Naveen Hegde
2017-12-26 16:29:37 +05:30
committed by GitHub
parent 489de17556
commit 58fec90013

View File

@@ -1,13 +1,13 @@
#include<iostream>
using namespace std;
int LinearSearch(int *array, int key)
int LinearSearch(int *array, int size, int key)
{
for (int i = 0; i < 10; ++i)
for (int i = 0; i < size; ++i)
{
if (array[i]==key)
{
return key;
return i;
}
}
@@ -17,19 +17,24 @@ int LinearSearch(int *array, int key)
int main()
{
int array[10];
int size;
cout<<"\nEnter the size of the Array : ";
cin >> size;
int array[size];
int key;
//Input array
cout<<"\nEnter the Array of 10 numbers : ";
for (int i = 0; i < 10; i++)
cout<<"\nEnter the Array of " << size << " numbers : ";
for (int i = 0; i < size; i++)
{
cin>>array[i];
}
cout<<"\nEnter the number to be searched : ";
cin>>key;
int index=LinearSearch(array, key);
int index=LinearSearch(array, size, key);
if (index!=-1)
{
cout<<"\nNumber found at index : "<<index;