0

I am having trouble testing my bubble sort algorithm. I have used gdb but the output from gdb isn't telling me anything I understand at this point (even after reading several tutorials, etc.) Find.c compiles at this point, but I don't think my sort algorithm actually does anything. Also, I have tried using printf, but I get compiler errors no matter where I try and put it. Any suggestions?

void sort(int values[], int n)
{
    int sorted = false;
    do
    {
        for(int i = 0; i < n; i++)
        {
            for(int j = 0; j < i; j++)
            {
                int k = (j +1);
                if ((values[j]) > (values[k]))
                {
                    int swap = j;
                    j = k;
                    k = swap;
                    sorted = true;
                }
            }
            n = n - 1;
        }
    }
    while(sorted == true);
    return;
}
1

The simple approach works. Just before the return, create a for loop and print out the array in order.

Having said that, your sort isn't working. You do a great job of swapping j and k. The problem is that you need to swap values[j] and values[k]. Also, since k always equals j+1, you could simply use j+1 instead.

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

2
  • I don't know which int to call in my printf statement. The only int that can be used just before return and not get an undeclared identifier is n. That doesn't print out the values[ ]. Also, can you clarify what you meant by "since k always equals j+1, you could simply use j+1 instead. Thanks – Flesheaters Sep 8 '16 at 3:25
  • I figured out the answers to both of my questions and have gotten printf to work. However it still isn't sorting. I have some work to do! – Flesheaters Sep 8 '16 at 4:38
0

start j =i because you don't have to recheck sorted numbers void sort(int values[], int n) { int sorted = false; do { for(int i = 0; i < n; i++) { for(int j = i; j < i; j++) { int k = (j +1); if ((values[j]) > (values[k])) { int swap = j; j = k; k = swap; sorted = true; } } n = n - 1; } } while(sorted == true); return; }

You must log in to answer this question.

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