Fundamentals 3 min read

Bubble Sort Algorithm Explained with PHP Implementation

This article explains the Bubble Sort algorithm, its O(n²) time and O(1) space complexities, describes the step‑by‑step sorting process, provides a complete PHP implementation, and shows sample input and output to illustrate how the algorithm orders data.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Bubble Sort Algorithm Explained with PHP Implementation

Bubble Sort, known as "Bubble Sort" in English and "泡沫排序" in Taiwan, is an in‑place, stable sorting algorithm with time complexity O(n²) and space complexity O(1).

When sorting in ascending order, the algorithm repeatedly compares adjacent elements and swaps them if they are out of order, moving the largest unsorted element to the end of the list after each pass.

The process continues until a full pass makes no swaps, indicating that the list is sorted.

Below is a PHP implementation of Bubble Sort that supports both ascending and descending order:

$arr[$j]) || (!$sort && $arr[$j - 1] < $arr[$j])) {
                list($arr[$j], $arr[$j - 1]) = array($arr[$j - 1], $arr[$j]);
            }
        }
    }
    return $arr;
}
$arr = [1, 6, 8, 10, 2, 5, 7, 9, 1];
echo "Original data:\n";
print_r($arr);
echo "Sorted in ascending order:\n";
print_r(bubble_sort($arr));
?>

The execution result shows the original array and the sorted array in ascending order:

Original data:
Array
(
    [0] => 1
    [1] => 6
    [2] => 8
    [3] => 10
    [4] => 2
    [5] => 5
    [6] => 7
    [7] => 9
    [8] => 1
)
Sorted in ascending order:
Array
(
    [0] => 1
    [1] => 1
    [2] => 2
    [3] => 5
    [4] => 6
    [5] => 7
    [6] => 8
    [7] => 9
    [8] => 10
)

Illustrative images from Wikipedia are included to help visualize the sorting process.

Feel free to like and share if you found the article helpful.

Sorting AlgorithmphpCode Examplebubble sortalgorithm fundamentals
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.