0

I try inputting ./find 31 and then the list 30, 31, 32 and it still says it can't find the needle in the haystack. :( I don't know if it's my search function, my sort function, or both. Help! The program compiles correctly, so I don't know what the problem is...

Here's my code, please let me know what I'm doing wrong.

bool search(int value, int values[], int n)
{
// implement a searching algorithm

    int beginning = 0;
    int ending = n - 1;

    while (ending >= beginning)
    {
        int midpoint = (beginning + ending)/2;

        if (values[midpoint] == value)
        { 
            return true;
        }
        else if (values[midpoint] > value)
        {    
            ending = midpoint - 1;
        }
        else
        {
            beginning = midpoint + 1;    
        } 

    }
    return false;
}

void sort(int values[], int n)
{
// implements a bubble sort sorting algorithm
int counter;

    do
    {
        counter = 0;

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

}

1 Answer 1

3

Think about what is happening in your sorting algorithm. When you are doing a swap algorithm, you need a third variable to store the value of one variable temporarily. For example, if we have a = 5 and b = 3, if we do:

a = b    // a is now equal to 3, b is still equal to 3
b = a    // b is assigned 3 but it is already 3

You clobber the value you want to swap if you don't store it somewhere first. Instead, make a temporary variable of the same type you are swapping, give it the value of one of your variables, then you can swap the second variable value to the first and the stored value to the second variable. That's a mouthful, so another example:

int c = a    // our value of a is now stored (a = 5, b = 3, c = 5)
a = b        // the value of b is swapped into a (a = 3, b = 3, c = 5)
b = c        // the value stored in c is now swapped into b (a = 3, b = 5, c = 5)

One other thing, think about how far that loop will try to check the array. When i = n-1, what indices will it try to use? Or put another way, if you're comparing a pair of values adjacent to each other, and the front one is the last item in the array, what is the second value you're checking?

Your search algorithm looks ok, but it would make it a bit more readable if you used a different name. value and values[] look almost identical. It's not wrong, but maybe target would be more descriptive.

You must log in to answer this question.

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