0

Please help, I have encounter some problem with this helper file. This seems like a simple one, but somehow I'm not finding the needle after executing "./generate 1000 50 | ./find 127" I have try checking for error in my code like 20 different ways and this took me super long but I still can't find any problem with this code, can someone help?

bool search(int value, int values[], int n)
{
// TODO: implement a searching algorithm



for (int a = 0; n>a; a++)
{
if (values[a] == value)
{
return true;
break;
}
else
{
return false;
}
}
return false;
}

/**
* Sorts array of n values.
*/
void sort(int values[], int n)
{
// TODO: implement an O(n^2) sorting algorithm
return ;
}
0

Your problem is the else clause in the search() function. Think about program flow. As written, the code gets the first element in the array. If it is a match, it returns true. BUT, if it doesn't match value, then the code drops to the else clause and executes the return false;, immediately exiting the search() function. You never test more than the first element in the array.

You shouldn't have an else clause. If the array element and the target value don't match, then you shouldn't do anything, except to let the loop move on to the next element.

The return false should only be executed after the for loop has fully executed.

If this answered your question, please click on the check mark to accept the answer. Let's keep up on forum maintenance. ;-)

2
  • YES OMG!!!! Thank you soooo much!!!!! you are a life saver!!!! – Leon Nov 19 '15 at 3:13
  • BTW, teh break statement is meaningless dead code. As soon as you execute a return command, the flow of control immediately goes back to the calling code and no further commands in the function are executed. So, the break code will never be executed. – Cliff B Nov 19 '15 at 3:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .