0

I'm working on implementing a binary sort.

I don't understand the error in my code. I'm getting that error 3 times, on line 24, 43, and 48. Those are the three conditionals with the find(value, low, high, value[]). Anyone spot the error/point me on the right path?

#include <cs50.h>
#include <stdio.h>

#include "helpers.h"

bool find(int value, int low, int high, int values[]);
/**
* Returns true if value is in array of n values, else false.
*/
bool search(int value, int values[], int n)
{

int low = 0;
int high = n;
if (find(value, low, high, values[]))
{
    return true;
}
else 
{
    return false;
}

}

bool find(int value, int low, int high, int values[])
{

if ( low != high)
{
    int mid = (low + high) / 2;

    if (value > values[mid])
        {
            find( value, mid + 1, high, values[]);
        }

    if ( value < values[mid] )
        {
            find ( value, 0, mid - 1, values[]);
        }
    else
    {
        return true;
    }
}
else 
{ 
    if (value == values[low])
    {
        return true;
    }
    else
    {
        return false;
    }
}
}
2

To answer your specific question about the errors, you have a problem in how you call find().

if (find(value, low, high, values[]))

The problem is that you are trying to pass the address of the array, but including the [] brackets is incorrect syntax. The compiler then expects a number to be inside the brackets. The only place that you should have empty brackets is in the prototype in the .h file or at the beginning of the function itself.

Drop the brackets and these errors go away. Then you can move on to the other errors in the code. ;-)

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

1
1

You don't want to be implementing find() using an if-then statement, it will only execute once and then move on. You want your code to keep iterating/looping until you find what you're looking for. That means you should use a while loop to keep adjusting the values of low and high until you zero in on value. Only then do you exit your code with a return value of true or false if not found.

3
  • Actually, what Elijah is trying to do is to recursively call the function. Although it has some bugs that need to be worked out, the form that he has with if/else statements is essentially how to do it. The biggest problem there is that he's not handling the returns from the recursive calls correctly. For more in-depth explanation, see cs50.stackexchange.com/q/9691/4847
    – Cliff B
    Nov 13 '15 at 5:52
  • You're right, I missed the way he's calling the function again within the function body itself. My bad.
    – ronga
    Nov 14 '15 at 5:33
  • Thank you Cliff for the advice! That resource helped to solve that issue and I doubt I would have known to do something like that without you! Nov 14 '15 at 23:45

You must log in to answer this question.

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