0

this is my code for binary search.

  bool binary(int key, int array[], int min, int max);

  bool search(int value, int values[], int n)
  {

     if( n< 0)
     {
         return false;
     }
     else
     {
         return binary(key,array,min,max);
     }
  }

bool binary(int key, int array[], int min, int max)
{
    int mid = (min + max)/2;

    if( array[mid] == key)
    {
        return true;
    }
    else if( array[mid]> key)
    {
        return binary(key,array,min,mid-1);
    }
    else if(array[mid]< key)
    {
        return binary(key,array,mid+1,max);
    }
    return false;

}

void sort(int values[], int n)
{
    int min;
    int swap;

    for(int i = 0; i > n; i++)
    {
        min = i;
        for(int j = 0; j == n; j++)
        {
            if(values[j] > values[min])
            {
                min = j;
                if (min != i)
                {
                    swap = values[min];
                    values[min] = values[i];
                    values[i] = swap;
                }

            }
        }
    }
    return;
}

after compiling it shows error saying that - helpers.c:31:22: error: use of undeclared identifier 'key' return binary(key,array,min,max); ^ helpers.c:31:26: error: use of undeclared identifier 'array' return binary(key,array,min,max); ^ helpers.c:31:32: error: use of undeclared identifier 'min' return binary(key,array,min,max); ^ helpers.c:31:36: error: use of undeclared identifier 'max' return binary(key,array,min,max); even though i have defined them above in line 1. why this error is coming? also is this way of making the code in accordance with condition of pset3 as they have asked to not change the defination of search. please help me.

0

"...even though i have defined them above..." That's not exactly true. You have only defined them as parameters for the function binary() by creating the prototype for binary(). They will only function as local variables inside binary(). When you then try to call binary() from inside search, they don't exist there. They also don't exist as global vars. Since they don't exist where you are trying to use them, you get the undeclared identifier errors.

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

3
  • okay, i think i got it. though can you tell me if my sort code is correct because even after doing the changes my program is not able to find 127 in haystack. thank you for your help. – YASHI KHATRI Sep 22 '16 at 3:29
  • No, sort is definitely broken. You can verify this by adding a printf in a for loop at the end of the sort routine to print out the list. Hint: Look at your for loop setup. – Cliff B Sep 22 '16 at 3:48
  • thank you. i realised my mistake. – YASHI KHATRI Sep 22 '16 at 4:22

You must log in to answer this question.

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