HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcMinor

Comparing two bubble sort algorithms

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
comparingalgorithmstwobubblesort

Problem

I'm learning C and I've got to a point learning about different sorting algorithms. Before seeing how it was done, I wanted to try doing it myself based on what I read on how it's working.

int temp;
    for(int i = 0; i  arr[j + 1])
            {
                temp = arr[j + 1];
                arr[j + 1] = arr[j];
                arr[j] = temp;
            }
        }
    }


This is what the code from where I learn looks like:

for(int i = 0; i  arr[i+1]))
       {
                  int tmp = arr[i];
                  arr[i] = arr[i + 1];
                  arr[i + 1] = tmp;
                  i = -1;
       }
}


Now, obviously they're different, but is one more efficient in someway than the other? Did I do something that is less efficient than their code?

Solution

Your implementation

Your implementation is mostly pretty good. I'd just make a few minor changes:

  • int temp should be declared in the tightest scope possible — namely, inside the if block. Localizing the variable further makes it harder to misuse and easier to understand. I'd also rename temp to swap to make its purpose clearer. (Naming a variable temp is usually a bad idea, in my opinion.)



  • int temp is at the wrong level of indentation. Maybe you just made an error when pasting the code here?



  • There is a space after if, but not after for. Be consistent. I recommend putting the space there to distinguish those keywords from function calls.



-
The `j

Code Snippets

for (int ii = SIZE - 1; ii > 0; ii--)
{
    /* Let the largest element bubble up to the end */
    for (int j = 0; j < ii; j++)
    {
        if (arr[j] > arr[j + 1])
        {
            int swap = arr[j + 1];
            arr[j + 1] = arr[j];
            arr[j] = swap;
        }
    }
}

Context

StackExchange Code Review Q#62091, answer score: 2

Revisions (0)

No revisions yet.