I have tried to use a do-while outer loop with a for inner loop to implement bubble sort, but it appears to be executing once through the for loop and then not satisfying the while condition. The code is as follows:
int main(void)
{
int n = 5;
int values[] = {0,5,4,3,2};
// Advance through unsorted part of list
int repeater = 0;
int k = 0;
do
{
int repeater = 0;
// Iterate through array
for (int i = 0; i < n - k - 1; i++)
{
// Swap if left element is larger than right element
if (values[i] > values[i + 1])
{
int temp = values[i + 1];
values[i + 1] = values[i];
values[i] = temp;
repeater++;
}
}
// Increment number of sorted elements
k++;
}
while (repeater > 0);
}
When I run this code, the array values
ends up as {0,4,3,2,5}
gdb didn't really help explain what was going on.
On the first time through the for loop nothing happens (as expected because 0 < 5). On the 2, 3, and 4 times through the value 5 is correctly swapped and the variable repeater increments by 1.
The next time, the for loop does not execute because i == n
(not < n). The code appropriately then skips to increment k
. If in gdb I print the value of repeater after k
is incremented, it still shows 3.
But when the next curly brace is executed, the value of repeater suddenly changes to 0, which does not satisfy the while condition, and therefore terminates the program.
Can anyone explain what's going on here? I'm asking more for the sake of learning, because I plan to stop using a do-while loop for sort. This is my second attempt at doing it!