0

Why is this program not returning true when value is in values?

bool search(int value, int values[], int n)
{
// TODO: implement a searching algorithm
int start = 0; int end = n-1; int k = 0; 
//return true;
k = (int) (start + end)/2;
while(start <= end)
{
   if (values[k] == value)
   {
       return true;
   }
   else if (values[k] > value)
   {
       end = k - 1;
   }
   else if (values[k] < value)
   {
       start = k + 1;
   }
   k = (int) (start + end)/2;
}
return false;

}

I'm getting output Didn't find needle in haystack. for both ./generate 1000 | ./find 127 and ./generate 1000 | ./find 128. Given below is my sort function.

void sort(int values[], int n)
{
int counter = 5;
do
{
    counter = 0;
    for(int i = 0; i < n-1; i++)
    {
        int temp = 0;
        for (int j = i+1; j<n; j++)
        {
            temp = values[i];
            if(values[i] > values[j])
            {
                values[i] = values[j];
                values[j] = temp;
                counter = counter + 1;
            }
        }
    }
}
while (counter != 0);
}
0

This code looks fine to me (I would have put the k = ... at the beginning of the loop, so there's no need for a second copy). Maybe your error is in sort, not search. Binary search requires a sorted array.

Does linear search work? If so, at least you are not losing the element searched for. Which still does not guarantee any correctness of the sort function.

3
  • I've included my sort function in the question part. It is working fine i guess.
    – Joe
    May 19 '17 at 11:02
  • @Blauelf Indeed both my functions are correct. I've made a mistake while checking, I forget to include the seed while calling generate function.
    – Joe
    May 19 '17 at 11:08
  • Did not spot that one. Great you found it!
    – Blauelf
    May 19 '17 at 12:38

You must log in to answer this question.

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