Bubble sort is one of the simplest sorting methods. It works by comparing two numbers next to each other and swapping them if they are in the wrong order. This process repeats until the whole array is sorted.
It is not the fastest way to sort data, but it is easy to understand and good for learning.
How it works
1. Start from the first element
2. Compare it with the next one
3. Swap them if needed
4. Move one step forward
5. Repeat until the end of the array
6. Do the same process again until no swaps are needed
PHP Example
<?php
function bubbleSort($numbers) {
$totalCount = count($numbers);
for ($pass = 0; $pass < $totalCount; $pass++) {
for ($index = 0; $index < $totalCount - $pass - 1; $index++) {
if ($numbers[$index] > $numbers[$index + 1]) {
// swap
$temporaryValue = $numbers[$index];
$numbers[$index] = $numbers[$index + 1];
$numbers[$index + 1] = $temporaryValue;
}
}
}
return $numbers;
}
$numbers = [5, 3, 8, 4, 2];
$sorted = bubbleSort($numbers);
print_r($sorted);
Output
Array
(
[0] => 2
[1] => 3
[2] => 4
[3] => 5
[4] => 8
)
When to use it
Bubble sort is fine for small lists or for learning. It is not good for large data because it is slow compared to other methods.
Summary
Bubble sort is simple and easy to code in PHP. It helps you understand how sorting works, even if you will not use it in real projects often.