0

I dealt with sorting in a separate file first, and then I dealt with searching in another file. They seem to work okay or at least worked for the numbers I feed in, but when I put them in helpers and compile the file the result is always "Didn't find needle in haystack." Can anyone tell me what's wrong with my code? Thank you!!

#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)
{
    if (value < 1)
    {
        return false;
    }
    if (value > 0)
    {
        int first = 0;
        int last = n - 1;
        int m = (first + last) / 2;
        while ((first <= last) && (m != last))
        {
            if (value == values[m])
            {
                return 0;
            }
            if (value > values[m])
            {
                first = m + 1;
                m = (first + last) / 2;
            }
            if (value < values[m])
            {
                last = m;
                m = (first + last) / 2;
            }
        }

    }
    return false;
}


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

Your search function never returns true. Ever.

if (value == values[m])
{
    return 0;
}

return 0 is the same as return false. It should be return 1 or return true.

You must log in to answer this question.

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