0

After reading the other questions, I still don't get how to check it.

I tried to use gdb on ./find, but while I ran it, I could only see what was expected. Then, while typing n, it said "in fileops.c" forever.

Then, I tried using printf. I typed in printf ("%i\n", values[i]); underneath the swap, and when I ran find, nothing happened.

Also, if you could, could you tell me if my code is off anywhere? That would be great!

void sort(int values[], int n)
{
    int compare = 0;

    if (n <= 1) return;

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

        int temp = values[i];
        values[i] = values[compare];
        values[compare] = temp;
    }
}

3 Answers 3

0

I'm not sure what problems you are having with gdb. You'd have to post examples of the commands that you are entering along with the results produced so that we could see what's going on. In any case, you should review the class materials and you should google for gdb tutorials until you're comfortable with it.

The issue with the print statement would depend on exactly where it was placed. It's possible that it was never executed.

The sort needs a lot of work. The biggest problem that I see is this: the reassignment of i can cause none or a lot of elements in the list to be skipped instead of sorted, depending on the input. You should spend some time with paper and pencil and manually figure out what the code does, tracing through it on paper with a couple of different sample inputs.

0

The main problem is the assignment of i in the if statement.The easiest way to rectify your code is to delete that assignment statement and bring the swapping process done later inside the body of if statement.By doing this you ensure that smallest element of a later part of the array comes to the front and the elements are arranged in sorted order.This sorting algorithm is not a standard one but it is O(n^2) as the problem requires it to be.

0

The problem with your code right now is that you are changing the counter variable in your for loop, i. So when this happens, you might be skipping over some iterations. I would suggest using a variable called max, which would be the index of the larger number of the two, and then swap.
Hope this helped!

You must log in to answer this question.

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