Бортовой журнал Ктулху

Bubble Sort in PHP — How the “Bubble” Really Works

Most developers use sort() and never think about what’s inside. But classic algorithms like Bubble Sort are perfect for understanding how sorting logic works step by step. Let’s look at a clean PHP implementation.

 

1

$arr = [11,5,2,77,9,-5,4,0,88,99];
function getMax(array &$arr, int $limit): void {
for ($j = 0; $j < $limit; $j++) {
 if ($arr[$j] > $arr[$j + 1]) {
  $tmp = $arr[$j];
  $arr[$j] = $arr[$j + 1];
  $arr[$j + 1] = $tmp;
  }
}
}
$n = count($arr);
for ($i = 0; $i < $n - 1; $i++) {
 getMax($arr, $n - 1 - $i);
}
var_dump($arr);

How it works

Each pass “bubbles up” the largest number to the end of the array.

On the first pass, the biggest element moves to the last position.

On the next pass — the second largest. And so on.

The outer loop runs n-1 times, and the inner loop stops earlier every time ($n - 1 - $i) — because the end is already sorted. After each pass, the unsorted part of the array becomes smaller. This visual idea of elements bubbling up through comparisons is why it’s called Bubble Sort.