Skip to content
PHP Logo

What is the purpose of the bubblesort function in the provided PHP code?

The purpose of the bubblesort function in the provided PHP code is to sort an array of numbers in ascending order. The bubblesort algorithm works by comparing adjacent elements in the array and swapping them if they are in the wrong order. This process is repeated until the array is sorted.

php
function bubblesort($arr) {
    $n = count($arr);
    do {
        $swapped = false;
        for ($i = 0; $i < $n - 1; $i++) {
            if ($arr[$i] > $arr[$i + 1]) {
                $temp = $arr[$i];
                $arr[$i] = $arr[$i + 1];
                $arr[$i + 1] = $temp;
                $swapped = true;
            }
        }
    } while ($swapped);
    
    return $arr;
}

// Usage
$arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
$arr = bubblesort($arr);
print_r($arr);