Please tell me what's wrong with this linear search algo!
#include <iostream>
using namespace std;
int searchlist();
int arrsize = 5;
int array [] = {1,2,3,4,5};
int main()
{
int results;
results = searchlist();
if(results == -1)
{ cout << "no good in the array" << endl;
}
else{
cout<< results << "has got juice" << endl;}
}
int searchlist()
{
int position =-1;
bool found= false;
int index= 0;
int value= 4;
while(index < arrsize && !found)
{
index = index + 1;
}
if( array[index] = value)
{
position= index+ 1;
found= true;
}
return position;
}
Please use code tags. They make the code easier to read.
The problem is that your
if() condition is outside the
while() loop.
Below is your current code, unchanged except for layout.
What's more the
if() contains an assignment
= and not a comparison
== as the condition.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
int searchlist()
{
int position =-1;
bool found= false;
int index= 0;
int value= 4;
while(index < arrsize && !found)
{
index = index + 1;
}
if( array[index] = value)
{
position= index+ 1;
found= true;
}
return position;
}
|
These mistakes are easy to fix, so try to do it yourself, and post back if you need more help.
Last edited on
Oh yes. Got it. Thank you :)
Will keep the hashtags in mind.