0

As suggested I start with linear search to make sure the bubble sort is working. When I test my code as mentioned with ./generate 1000 50 | ./find 127, the result I have is:

haystack[0] = Retry: 
Didn't find needle in haystack.

Please, help me what to do next. Is it my code that is not good or is there a step that I'm missing to do to link all the files?

Here's my code:

bool search(int value, int values[], int n)
{
    // search by linear 
    for (int i = 0; i < n; i++)
    {
        if n < 0;
        return false;

    else
        if (values[i] == value)
        return true; 

    return false;
}


/**
 * Sorts array of n values.
 */
void sort(int values[], int n)
{
    // sort by bubble sort 
    for (int j = 0; j < n - 1; j++)
    {
        for (int k = 0; k < n - j - 1; k++)
            if (values[k] > values[k + 1])
                {
                    int temp = values[k];
                    values[k] = values[k + 1]; 
                    values[k + 1] = temp;
                }
    }
    return;
}

2 Answers 2

1

Is bubble sort working? Is linear search working? These are two different questions. I'll skip the sort for now, since the linear search is the immediate problem. (Besides, you can test the sort simply by adding some temporary code to print out the list at the end of sort.)

Let's take a close look at the linear search function. It checks whether n<0, which is good, but it is inside the for loop! This means that it will be checked on EVERY pass. It only needs to be done once, so it can be done before the loop.

Next, look at what else is inside the loop. if (values[i] == value) return true; This is good. What's the next line inside the loop? return false; This means that if the needle isn't the very first value checked, it's going to execute a return false command. It will never make it to the end of the first pass through the loop.

The return false statement is supposed to be the catchall return at the end of the function in case the target is not found. Where should it be?

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

0

The code for linear search is problematic. Consider the following pseudocode:

for every element in the list
    if needle is equal to that list element
       return true (needle was found)
return false (needle was not found)

You can return true in the for loop if the element is found and return false outside of it. The only way you'll break outside the loop is if nothing returns true.

You must log in to answer this question.

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