I saw a piece of bubble sort code, and initially I thought the code was wrong. But after compiling and running, it surprised me that it really works. I want to know how the second statement in the first for loop is not a condition, but a destination. Also, how does this code not go into an infinite loop?
PS: It will generate a warning: "suggest parentheses around the assignment used as the value of the truth [-Wparentheses]" complaining about the first for loop. Surprisingly, this is not a mistake.
#include <iostream>
void bubblesort(int A[], int n)
{
for (bool sorted = false; sorted = !sorted; n--)
{
for (int i = 1; i < n; ++i)
{
if (A[i-1] > A[i])
{
int tmp = 0;
tmp = A[i];
A[i] = A[i-1];
A[i-1] = tmp;
sorted = false;
}
}
}
}
int main()
{
int a[5] = {1,4,5,2,3};
bubblesort(a, 5);
for (unsigned int i = 0; i < 5; ++i)
{
std::cout << a[i] << std::endl;
}
return 0;
}
source
share