Search code examples
javaloopsbubble-sort

Clarifications on bubble sorting in Java


public void bubbleSort(int[] array) {
     int n = array.length;
     boolean madeSwap = true;// I don't understand the purpose of boolean
     while(madeSwap) {
           madeSwap = false;
           //Scanning           
           for (int j = 0; j < n - 1; j++) {
                if (array[j] > array[j+1] ) {
                     //Swapping                     
                     int temp = array[j];
                     array[j] = array[j+1];
                     array[j+1] = temp;
                     madeSwap = true;//
                }
           }
     }
}

Hello, I've be given this code for bubbleSort in my class. I don't really understand what does the boolean exactly do in this context. Can someone clarify it for me? Thank you in advance!


Solution

  • Well, if the madeSwap flag remains true (i.e. the if statement was executed), then it means that the array isn't sorted yet.

    When that flag remains false, it means that the array has been sorted (i.e. no sorting needed).

    You could even rename it to needsSorting, would be much clearer.

    while (needsSorting) // <-- Loop 1
    {
        needsSorting = false; // Neah 
    
        // Go through the items in the array, and see if there are any suspicions
        for (...) // <-- Loop 2
        {
            // Do I still need to go over the loop again?
            if (successive elements are not in order)
            {
                // Switch elements here
                ...
                needsSorting = true; // Yep, make another pass over the array
            }
        }
    }
    

    If you still don't get it, watch a visual representation of the bubble sort, or go step by step with your code and watch your array values + their order.