Bubble Sort in PHP


Q. Write a PHP program for Bubble Sort

 <?php
// Define an array
$array = array(64, 34, 25, 12, 22, 11, 90);
$n = count($array);

// Bubble Sort logic
for ($i = 0; $i < $n - 1; $i++) {
    for ($j = 0; $j < $n - $i - 1; $j++) {
        if ($array[$j] > $array[$j + 1]) {
            // Swap elements
            $temp = $array[$j];
            $array[$j] = $array[$j + 1];
            $array[$j + 1] = $temp;
        }
    }
}

// Display sorted array
echo "Sorted array in ascending order: ";
foreach ($array as $value) {
    echo "$value ";
}
?>

Q. Write an algorithm for Bubble Sort in PHP

1. Start
2. Define an array array[]
3. Get the length of the array n
4. Loop i from 0 to n - 2:
    a. Loop j from 0 to n - i - 2:
5. If array[j] > array[j+1], swap array[j] and array[j+1]
6. Print the sorted array
7. End



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.