0
0
PhpProgramBeginner · 2 min read

PHP Program for Bubble Sort with Example and Explanation

A PHP program for bubble sort uses nested 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

Input[5, 2, 9, 1]
Output[1, 2, 5, 9]
Input[3, 3, 2, 1]
Output[1, 2, 3, 3]
Input[]
Output[]
🧠

How to Think About It

To sort an array using bubble sort, think of repeatedly passing through the list and comparing each pair of neighbors. If the left one is bigger, swap them. Keep doing this until no swaps are needed, meaning the list is sorted.
📐

Algorithm

1
Get the array to sort and find its length.
2
Repeat from the first element to the last unsorted element:
3
Compare each pair of adjacent elements.
4
If the left element is greater than the right, swap them.
5
Repeat the process until the entire array is sorted.
💻

Code

php
<?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);
?>
Output
Array ( [0] => 1 [1] => 2 [2] => 5 [3] => 9 )
🔍

Dry Run

Let's trace the array [5, 2, 9, 1] through the bubble sort code.

1

Initial array

[5, 2, 9, 1]

2

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]

3

Second pass comparisons and swaps

Compare 2 and 5, no swap; compare 5 and 1, swap -> [2, 1, 5, 9]

4

Third pass comparisons and swaps

Compare 2 and 1, swap -> [1, 2, 5, 9]

5

Array sorted

[1, 2, 5, 9]

PassArray 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

Using a while loop with a swapped flag
php
<?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);
?>
This approach stops early if no swaps happen, improving efficiency on nearly sorted arrays.
Using PHP's built-in sort function
php
<?php
$array = [5, 2, 9, 1];
sort($array);
print_r($array);
?>
This is the simplest and fastest way in PHP but does not teach the bubble sort algorithm.

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.

ApproachTimeSpaceBest For
Basic bubble sortO(n^2)O(1)Learning sorting basics
Bubble sort with swapped flagO(n) best, O(n^2) worstO(1)Nearly sorted arrays
PHP built-in sort()O(n log n)O(n)Real-world sorting
💡
Use a swapped flag to stop early if the array is already sorted to save time.
⚠️
Forgetting to reduce the inner loop range each pass causes unnecessary comparisons.