Bubble Sort Algorithm to Prevent Cycle

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;
}
+4
source share
4 answers

,

sorted = !sorted

sorted . , , .

(sorted = !sorted) == true

.

+6

C ++, . (= ==), .

, .

; , reset true, , , . , , , .

+3

. , sorted - true , .

1- :

for , . → false . , sorted- > true .

0

:

sorted != sorted

, . :

sorted = !sorted

By doing this, you simply deny the sort condition, i.e. it is assumed that an array that is unsorted is sorted. Then, if you traverse the full array without any replacement, the left side of the assignment is accepted as a condition (which is true in this case).

0
source

Source: https://habr.com/ru/post/1531470/


All Articles