PHP Program for Bubble Sort with Example and Explanation
for loops to repeatedly swap adjacent elements if they are in the wrong order, like for ($i = 0; $i < $n-1; $i++) { for ($j = 0; $j < $n-$i-1; $j++) { if ($arr[$j] > $arr[$j+1]) { swap }}}.Examples
How to Think About It
Algorithm
Code
<?php function bubbleSort(array &$arr): void { $n = count($arr); for ($i = 0; $i < $n - 1; $i++) { for ($j = 0; $j < $n - $i - 1; $j++) { if ($arr[$j] > $arr[$j + 1]) { $temp = $arr[$j]; $arr[$j] = $arr[$j + 1]; $arr[$j + 1] = $temp; } } } } $array = [5, 2, 9, 1]; bubbleSort($array); print_r($array); ?>
Dry Run
Let's trace the array [5, 2, 9, 1] through the bubble sort code.
Initial array
[5, 2, 9, 1]
First pass comparisons and swaps
Compare 5 and 2, swap -> [2, 5, 9, 1]; compare 5 and 9, no swap; compare 9 and 1, swap -> [2, 5, 1, 9]
Second pass comparisons and swaps
Compare 2 and 5, no swap; compare 5 and 1, swap -> [2, 1, 5, 9]
Third pass comparisons and swaps
Compare 2 and 1, swap -> [1, 2, 5, 9]
Array sorted
[1, 2, 5, 9]
| Pass | Array State |
|---|---|
| 1 | [2, 5, 1, 9] |
| 2 | [2, 1, 5, 9] |
| 3 | [1, 2, 5, 9] |
Why This Works
Step 1: Compare adjacent elements
The code compares each pair of neighbors using if ($arr[$j] > $arr[$j + 1]) to find if they are out of order.
Step 2: Swap if needed
If the left element is bigger, it swaps them using a temporary variable to hold one value.
Step 3: Repeat passes
The outer loop repeats the process enough times to ensure all elements bubble up to their correct position.
Alternative Approaches
<?php function bubbleSortWhile(array &$arr): void { $n = count($arr); do { $swapped = false; for ($i = 0; $i < $n - 1; $i++) { if ($arr[$i] > $arr[$i + 1]) { [$arr[$i], $arr[$i + 1]] = [$arr[$i + 1], $arr[$i]]; $swapped = true; } } $n--; } while ($swapped); } $array = [5, 2, 9, 1]; bubbleSortWhile($array); print_r($array); ?>
<?php $array = [5, 2, 9, 1]; sort($array); print_r($array); ?>
Complexity: O(n^2) time, O(1) space
Time Complexity
Bubble sort uses nested loops, each running up to n times, so it takes about n squared steps in the worst case.
Space Complexity
It sorts the array in place, so it only needs a small fixed amount of extra memory.
Which Approach is Fastest?
Using a swapped flag can reduce time on nearly sorted data, but built-in PHP sort is fastest overall.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Basic bubble sort | O(n^2) | O(1) | Learning sorting basics |
| Bubble sort with swapped flag | O(n) best, O(n^2) worst | O(1) | Nearly sorted arrays |
| PHP built-in sort() | O(n log n) | O(n) | Real-world sorting |