How does the bubblesortFor function differ from the bubblesortwhile function in terms of implementation and efficiency?
The bubblesortFor function uses a for loop to iterate through the array and compare adjacent elements, swapping them if they are in the wrong order. On the other hand, the bubblesortwhile function uses a while loop that continues iterating and swapping elements until no more swaps are needed. The bubblesortwhile function may be more efficient in some cases as it stops iterating once the array is sorted, while the bubblesortFor function always iterates through the entire array.
// bubblesortFor function
function bubblesortFor($arr) {
$n = count($arr);
for ($i = 0; $i < $n - 1; $i++) {
for ($j = 0; $j < $n - $i - 1; $j++) {
if ($arr[$j] > $arr[$j + 1]) {
$temp = $arr[$j];
$arr[$j] = $arr[$j + 1];
$arr[$j + 1] = $temp;
}
}
}
return $arr;
}
// bubblesortwhile function
function bubblesortwhile($arr) {
$n = count($arr);
$swapped = true;
while ($swapped) {
$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;
}
}
}
return $arr;
}