# CS50 Helpers.C Find Less, No Idea What's Going On

Final Code:

``````/**
* helpers.c
*
* Helper functions for Problem Set 3.
*/

#include <cs50.h>

#include "helpers.h"

/**
* Returns true if value is in array of n values, else false.
*/
bool search(int value, int values[], int n)
{
// TODO: implement a searching algorithm
if (n <= 0)
{
return false;
}
int min = 0;
int max = n - 1;

while (n > 0)
{
int mid = (max - min) / 2 + min;

if (value == values[mid])
{
return true;

}
else if (value > values[mid])
{
min = mid + 1;
}

else if (value < values[mid])
{
max  = mid - 1;
}

n = max - min + 1;

}

return false;

}

/**
* Sorts array of n values.
*/
void sort(int values[], int n)
{
int swap;
for (int i = 0; i < n-1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (values[j] >  values[j + 1])
{
swap = values[j];
values[j] = values[j + 1];
values[j + 1] = swap;
}

}
}
return;
}
``````

Both search and sort have problems. First, sort isn't complete. It only makes one pass through the list, so it will only bubble sort the largest value to the last position. I suggest a review of the lectures and class material on bubble sorts.

Second (and without doing an in-depth analysis), it looks like the search routine goes into an infinite loop when the target is not in the list. Note that all of the later tests that fail are cases where the target is not in the list.

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

• Hey, I edited my code and I tried fixing what you suggested but now I get the error when I try to make it.
– R_C
Commented Oct 1, 2017 at 23:12
• helpers.c:50:1: error: control may reach end of non-void function [-Werror,-Wreturn-type] } ^ 1 error generated.
– R_C
Commented Oct 1, 2017 at 23:12
• Self explanatory. See cs50.stackexchange.com/questions/2448/… Commented Oct 1, 2017 at 23:25
• I'm still not getting this. I added a "return false;" at the end outside of the while loop incase it does not find anything, but it still does not exit with false.
– R_C
Commented Oct 2, 2017 at 0:17
• nevermind, got it, will edit code for anyone else wondering!
– R_C
Commented Oct 2, 2017 at 0:38