How to write PHP code for bubble sort algorithm?

Below is an example code implementing the bubble sort algorithm using PHP language.

function bubbleSort($arr) {
    $len = count($arr);
    for ($i = 0; $i < $len - 1; $i++) {
        for ($j = 0; $j < $len - $i - 1; $j++) {
            if ($arr[$j] > $arr[$j + 1]) {
                // 交换位置
                $temp = $arr[$j];
                $arr[$j] = $arr[$j + 1];
                $arr[$j + 1] = $temp;
            }
        }
    }
    return $arr;
}

// 测试示例
$nums = array(5, 3, 8, 2, 1, 4);
$sortedNums = bubbleSort($nums);
echo "排序后的数组为:" . implode(", ", $sortedNums);

The bubbleSort function in the above code takes an array parameter $arr and sorts it using the bubble sort algorithm. The outer loop iterates the number of array elements minus one times to control the number of comparisons. In the inner loop, it iterates through the remaining unsorted elements and swaps their positions if the current element is larger than the next element. This way, each iteration will bubble the largest unsorted element to the end. Finally, it returns the sorted array.

In the example above, the given input array is [5, 3, 8, 2, 1, 4]. By calling the bubbleSort function and outputting the sorted array to the screen, the sorted result obtained is: 1, 2, 3, 4, 5, 8.

bannerAds