What is the purpose of the bubblesort function in the provided PHP code?
The purpose of the bubblesort function in the provided PHP code is to sort an array of numbers in ascending order. The bubblesort algorithm works by comparing adjacent elements in the array and swapping them if they are in the wrong order. This process is repeated until the array is sorted.
function bubblesort($arr) {
$n = count($arr);
do {
$swapped = false;
for ($i = 0; $i < $n - 1; $i++) {
if ($arr[$i] > $arr[$i + 1]) {
$temp = $arr[$i];
$arr[$i] = $arr[$i + 1];
$arr[$i + 1] = $temp;
$swapped = true;
}
}
} while ($swapped);
return $arr;
}
// Usage
$arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
$arr = bubblesort($arr);
print_r($arr);
Related questions
-
stack data structure PHP session form
-
How can PHP be used to manipulate or analyze images after they have been downloaded onto the server?PHP image manipulation image analysis
-
file_get_contents _CONF die