# pset3 binary search won't find values when at end of array

As the title says, the program doesn't pass the check when 42 is the last element of the array. I've seen a related post about this issue but it did not give me enough to fix the problem. The code is bellow:

``````bool search(int value, int values[], int n)
{
int s=0;
int e=n-1;
int m=((s+e)/2);

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

if (e<s)
{return false;}

if (values[m]>value)
{e=(m-1);}

if (values[m]<value)
{s=(m+1);}

m=((s+e)/2);

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

} while(!(values[m]==value));

return false;
}

/**
* Sorts array of n values.
*/
void sort(int values[], int n)
{
int counter=-1;

do
{counter=0;
for  (int i=0; i<n; i++)
if (values[i]>values[i+1])
{
int swap= values[i];
values[i]=values[i+1];
values[i+1]=swap;
counter=counter+1;
}
}while(counter!=0);

return;
}
``````

## 1 Answer

The problem isn't your search, it's your sort. If you output your sorted list at the end of the function, you'll find that the first element is 0 and the largest element of the original list has been lost.

There is a very simple fix to this bug, but since I don't think you've considered that the problem is in sort, I'll let you have a shot at finding it. ;-) If you can't, leave a comment and I'll point you in the right direction.

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

• Thank you for your response. I had actually thought I'd checked the sort part. I printed out the output using printF in the find file and it seemed to print number of elements I requested in the command line in order. – astro Oct 18 '16 at 13:07
• Ok. Based on your response and looking again at previous threads I changed "n" to n-1" as the limit to the for loop and this seemed to fix it. I spent so much time looking at the search code! However I still don't quite understand WHY the sort function lost the last element. Since it seems to be a relatively basic concept for arrays I will have to go over it some more to understand why it was misbehaving. – astro Oct 18 '16 at 14:29
• Because the limit was n and not n-1, it was allowing the sort routine to access undetermined data beyond the end of the array. (Commonly, this will turn out to be 0. ) Whatever that data is, it will sort it into the array. It also means that since a number was brought into the array, another number has to leave. This turns out to be the largest number in the list. – Cliff B Oct 18 '16 at 17:07
• Yeah I get it now. I thought I was in the clear because in the for loop limit I was not accessing a element outside of the array (using "<n"). But the problem was that the function reached outside of the array because it looks past the element it is iterated over to compare the value and switch. At least I think that's it. Thank you again. I may start looking at the questions and providing feedback to others where/if I can. – astro Oct 19 '16 at 18:25