0

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

1

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.

4
  • thank you very much! you showed me a big error that I missed but still i do have the same problem. I have before the loop m and k (k = n-1) and in the loop definition of l(middle point). in loop i am changing m (m+l+1) or k(k-l-1) and it is still running overload on cpu :( – koko loko Dec 13 '17 at 5:43
  • I don't really understand and hope you are changing to l + 1 and l - 1? – Blauelf Dec 13 '17 at 7:02
  • yes, if (value < values[l]) k -= (l - 1); else //(value > values[l]) m += (l + 1); and i have still the same problem :( – koko loko Dec 13 '17 at 15:08
  • Use = instead of -= and +=. I meant "change to", not "change by". – Blauelf Dec 13 '17 at 16:05

You must log in to answer this question.

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