Sorting Visualization

20
41
62
133
94
N =5

Custom Arr =

1x


    function bubbleSort(arr) {
        // Outer loop to traverse through all elements
        for (let i = 0; i < arr.length; i++) {
            // Flag to check if no swaps were made in the inner loop
            let noBreak = true;
    
            // Inner loop to compare adjacent elements and swap if necessary
            for (let j = 0; j < arr.length; j++) {
                // Compare adjacent elements and swap if necessary
                if (arr[j] > arr[j + 1]) {
                    let temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    // Set flag to false if a swap occurred
                    noBreak = false;
                }
    
                // Even if a swap didn't occur, the flag should remain false
                noBreak = true;
            }
    
            // If no swaps occurred in the inner loop, the array is sorted
            if (noBreak)
                break;
        }
        // Return the sorted array
        return arr;
    }