# pset3 find less comfortable helpers.c didn't found the needle!

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

int left = 0, right = n - 1;

// TODO: implement a searching algorithm
while (n > 0)
{
int middle = (left + right) / 2;

if (value == middle)
{
return true;
}
if (left == right && value != middle)
{
break;
}

else if (value > middle)
{
left = middle + 1;
}
else if (value < middle)
{
right = middle - 1;
}

}
return false;
}

/**
* Sorts array of n values.
*/
void sort(int values[], int n)
{
// TODO: implement an O(n^2) sorting algorithm  (selection sort)

for (int i = 0; i < n; i++)
{
int min = values[i];
// i2 as a second counter
for (int i2 = 0; i2 < n; i2++)
{
if (min > values[i2])
{
min = values[i2];

int temp = values[i];
values[i] = min;
min = temp;
}
}
return;
}
}
``````

when I run find.c it doesn't find the needle (but it finds few) and I don't know where the problem is. (I didn't change anything in find.c). Some help please.

Use `while (left <= right)` to loop as long as the search interval has elements. No need for `break;`.

You compare value `value` to index `middle`, but you have to compare value `value` to middle value `values[middle]`. You need three cases, one for `==`, one for `<`, one for `>` (the actions seem correct, though, just the conditions aren't)

You're trying to implement a selection sort. To do so, you have to store the index, not the value.

Your inner loop should start at index `i+1`, not `0`, you don't want to compare to elements you have already sorted.

Make sure to compare only index to index or value to value. So it becomes

``````int min = i;
``````

and

``````if (values[min] > values[i2])
{
min = i2;
}
``````

The swap then has to happen between `values[min]` and `values[i]`.

The swap should be inside the outer loop, but after the inner loop, and definitely not in the `if (values[min] > values[i2])` area.

Likewise, the `return` should be after the outer loop, not within, otherwise you would return after first swap.

• I think there is also a problem in the sorting algorithm because when I input sorted numbers it doesn't find the needle. but what is the problem there ? – SamGal Apr 4 '17 at 15:00
• You'd have to store the index, not the value of the smallest element. What use is it if you swap with a variable containing a copy of the smallest element when you don't replace the element itself? – Blauelf Apr 4 '17 at 15:25
• :( finds 42 in {42,40,39,41} now it doesn't work well with this but worked with all above (check50) (I changed min to values[min] ) so why it didn't find the number in this? :( finds 42 in {42,40,39,41} – SamGal Apr 4 '17 at 15:36
• Updated answer, as I initially had totally missed that you posted code for `sort`, too. – Blauelf Apr 4 '17 at 15:48
• It worked! I should focus more than I am. Thank you very much for your help! – SamGal Apr 4 '17 at 16:05