snippetcMinor
Comparing two bubble sort algorithms
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.
This is what the code from where I learn looks like:
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?
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:
-
The `j
Your implementation is mostly pretty good. I'd just make a few minor changes:
int tempshould be declared in the tightest scope possible — namely, inside theifblock. Localizing the variable further makes it harder to misuse and easier to understand. I'd also renametemptoswapto make its purpose clearer. (Naming a variabletempis usually a bad idea, in my opinion.)
int tempis 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 afterfor. 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.