PHP Program for Bubble Sort
Last Updated :
27 Dec, 2023
Improve
This article will show you how to sort array elements using Bubble Sort in PHP. Bubble Sort is a simple sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. The time complexity of this algorithm is quite high.
Bubble Sort Algorithm
Traverse the array from the left and compare the adjacent elements and the higher value is placed on the right side. In this way, the largest element is moved to the rightmost end at first. This process is then continued to find the second largest and place it and so on until the data is sorted.
Example: In this example, we will sort the array elements using the Bubble sort sorting algorithm in PHP.
<?php
function bubbleSort($arr) {
$n = count($arr);
// Traverse through all array elements
for ($i = 0; $i < $n - 1; $i++) {
for ($j = 0; $j < $n - $i - 1; $j++) {
// Swap if the element found is
// greater than the next element
if ($arr[$j] > $arr[$j + 1]) {
$temp = $arr[$j];
$arr[$j] = $arr[$j + 1];
$arr[$j + 1] = $temp;
}
}
}
return $arr;
}
// Driver code
$arr = [64, 34, 25, 12, 22, 11, 90];
$sortedArray = bubbleSort($arr);
// Print the sorted array
echo "Sorted array: "
. implode(", ", $sortedArray);
?>
Output
Sorted array: 11, 12, 22, 25, 34, 64, 90