# find problem with my code - CPU overload

I cannot figure out what is wrong with my code.

``````/**
* Returns true if value is in array of n values, else false.
*/
bool search(int value, int values[], int n)
{
// ensures that the n is non negative
if (n < 1)
return false;

else
{
//making ints for binary searching: m - far right; k - far right ; l - middle/avarage of m and k;
int m = 0;
int k = n;
int l = (m + k) / 2;
while (m <= k)
{

//if (l == 0)
//return false;

if (values[l] == value)
return true;

else
{

if (value < values[l])
l = (m + (l - 1)) / 2;

else //(value > values[l])
l = ((m + 1) + k) / 2;
}
}
return false; // this is done only to fix control may reach of on non-void function error
}
}

/**
* Sorts array of n values.
*/
void sort(int values[], int n)
{
// MY TAKE ON BUBBLE SORT
int swap = 0;
do
{
for (int i=0; i < n-2; i++)
{
swap = 0;
if (values[i] > values[i+1])
{
int temp = values[i];
values[i] = values[i+1];
values[i+1] = temp;
swap ++;
}
}
}while (swap != 0);
}
``````

I tryed different varations the best thing that I get from this code that it finds from time to time 42 when but when i run it with generate it is overload

You never update `m` or `k`, so the loop will go on.
Move the `l = (m + k) / 2;` into the loop. And instead of calculating a different `l` in your actions, change `m` or `k`, and let `l` re-calculate on next iteration.
Your condition in `while` matches a version where you initialise `k` to `n-1`, not `n`.
• I don't really understand and hope you are changing to `l + 1` and `l - 1`? – Blauelf Dec 13 '17 at 7:02
• Use `=` instead of `-=` and `+=`. I meant "change to", not "change by". – Blauelf Dec 13 '17 at 16:05