Search code examples
javawhile-loopbubble-sort

I can't understand the while loop condition in bubble sort


First, I do understand what the for loop does and what the if block does

The part that I don't understand is !isSorted, if originally isSorted set to false, does !isSorted mean that it will set the while loop to true?

If yes, how come the loop go once again after there was a swap and isSorted flagged to false?

Apologies if I could not express myself clearly

It's working, but why it's working ?

public class BubbleSorting {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        int[] massiv =  {2,14,8,90,97,44,23,78, 11,1,46, 55, 105,64};
        int buffer;
        boolean isSorted = false;

        while(!isSorted){
            isSorted = true;
            for(int i = 0; i<massiv.length-1; i++){
                if(massiv[i]>massiv[i+1]){
                    buffer = massiv[i];
                    massiv[i] = massiv[i+1];
                    massiv[i+1] = buffer;
                    isSorted = false;
                }
            }
        }
        System.out.println(Arrays.toString(massiv));
    }
}

Solution

  • Tigran, in response your latest comment, I'll try to explain in a simple way that is easy to understand.

    A conditional (or conditional statement), in Java or most other programming languages, is a statement that performs different actions depending on whether a certain condition is true or false.

    In this case, the condition is the value of isSorted. The variable isSorted is a boolean variable, so it can have a value of either true or false.

    When we get to a line that says:

    while(isSorted)
    

    we are checking the condition in parentheses, which is isSorted. This means we are checking if isSorted is true. If it is, then we perform the action (enter the loop). If not, we do not.

    The "!" symbol means negation - and when used before a condition inside a conditional statement, it means "the opposite of the condition".

    So in the line:

    while(!isSorted)
    

    we are checking if the opposite of the isSorted condition is true, meaning isSorted is false. If it is, then we perform the action (enter the loop). If not, we do not.

    So in this case, we will only enter the while loop if the value of isSorted is false. If the value becomes true, we will stop entering the loop.