Loading...
0/0
Bubble Sort
Time: O(n²)Space: O(1)
Repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted.
Tips: Simple to understand but inefficient for large datasets.
Real World: Optimistically re-rendering a list that is already mostly sorted, where only a few elements are out of place.
Source
bubble-sort.php
1function bubbleSort(&$arr) {
2 $n = count($arr);
3 for ($i = 0; $i < $n - 1; $i++) {
4 for ($j = 0; $j < $n - $i - 1; $j++) {
5 // Compare adjacent elements
6 if ($arr[$j] > $arr[$j + 1]) {
7 // Swap
8 $temp = $arr[$j];
9 $arr[$j] = $arr[$j + 1];
10 $arr[$j + 1] = $temp;
11 }
12 }
13 }
14}