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.
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:
<?php
function bubble_sort($arr, $sort = true){
if (empty($arr) || !is_array($arr)) {
return false;
}
$count = count($arr);
for ($i = 0; $i < $count; $i++) {
for ($j = 1; $j < $count - $i; $j++) {
if (($sort && $arr[$j - 1] > $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:
";
print_r($arr);
echo "Sorted in ascending order:
";
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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
