PHP Program to Implement Bubble Sort

PHP Program to Implement Bubble Sort

Sorting is one of the most important concepts in programming. Among the simplest sorting algorithms is Bubble Sort, which is often the first algorithm beginners learn. Bubble Sort works by repeatedly comparing adjacent elements in an array and swapping them if they are in the wrong order. This process continues until the array is completely sorted. While it may not be the fastest sorting method for large data, its simplicity makes it perfect for understanding the fundamentals of algorithm design and array manipulation.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Bubble Sort is widely used for educational purposes and small datasets. By studying it, beginners learn how to manipulate arrays, perform conditional checks, and implement loops. PHP developers can use it to sort numbers, strings, or even more complex data structures with minor adjustments. In this article, we will explore multiple ways to implement Bubble Sort in PHP, helping you understand the algorithm deeply.

Program 1: Basic Bubble Sort Using Loops

This first example shows a simple implementation of Bubble Sort using nested loops. It compares each element with the next one and swaps them if necessary.

<?php

function bubbleSortBasic($array) {

    $n = count($array);

    for ($i = 0; $i < $n - 1; $i++) {

        for ($j = 0; $j < $n - $i - 1; $j++) {

            if ($array[$j] > $array[$j + 1]) {

                $temp = $array[$j];
                $array[$j] = $array[$j + 1];
                $array[$j + 1] = $temp;

            }

        }

    }

    return $array;

}

$data = [5, 2, 9, 1, 5, 6];

$sorted = bubbleSortBasic($data);

print_r($sorted);

?>

This program repeatedly scans the array, pushing the largest element to the end on each pass, much like bubbles rising to the surface. Beginners can see how nested loops interact and how the swapping logic keeps the array moving toward a sorted state.

Program 2: Bubble Sort With Early Termination

This version improves efficiency by stopping the sorting process if no swaps occur in a pass, indicating that the array is already sorted.

<?php

function bubbleSortOptimized($array) {

    $n = count($array);

    for ($i = 0; $i < $n - 1; $i++) {

        $swapped = false;

        for ($j = 0; $j < $n - $i - 1; $j++) {

            if ($array[$j] > $array[$j + 1]) {

                $temp = $array[$j];
                $array[$j] = $array[$j + 1];
                $array[$j + 1] = $temp;

                $swapped = true;

            }

        }

        if (!$swapped) {
            break;
        }

    }

    return $array;

}

$data = [3, 1, 4, 2, 5];

$sorted = bubbleSortOptimized($data);

print_r($sorted);

?>

Here, a $swapped flag monitors whether any swaps happen in a pass. If the array is already sorted before completing all iterations, the algorithm stops early. This teaches beginners about small optimizations that can make an algorithm more efficient.

Program 3: Recursive Bubble Sort

This program demonstrates how Bubble Sort can also be implemented recursively, instead of using loops. Each recursive call processes a smaller portion of the array until it is fully sorted.

<?php

function bubbleSortRecursive($array, $n = null) {

    if ($n === null) {
        $n = count($array);
    }

    if ($n == 1) {
        return $array;
    }

    for ($i = 0; $i < $n - 1; $i++) {

        if ($array[$i] > $array[$i + 1]) {

            $temp = $array[$i];
            $array[$i] = $array[$i + 1];
            $array[$i + 1] = $temp;

        }

    }

    return bubbleSortRecursive($array, $n - 1);

}

$data = [6, 2, 8, 4];

$sorted = bubbleSortRecursive($data);

print_r($sorted);

?>

Recursion gives a new perspective on Bubble Sort. Instead of iterating with loops, each function call handles a portion of the array. Beginners learn how recursion can replace iteration in algorithm design.

Program 4: Bubble Sort for Strings

Bubble Sort is not limited to numbers. This version demonstrates sorting an array of strings alphabetically.

<?php

function bubbleSortStrings($array) {

    $n = count($array);

    for ($i = 0; $i < $n - 1; $i++) {

        for ($j = 0; $j < $n - $i - 1; $j++) {

            if (strcmp($array[$j], $array[$j + 1]) > 0) {

                $temp = $array[$j];
                $array[$j] = $array[$j + 1];
                $array[$j + 1] = $temp;

            }

        }

    }

    return $array;

}

$data = ["Mango", "Apple", "Banana", "Cherry"];

$sorted = bubbleSortStrings($data);

print_r($sorted);

?>

Using strcmp allows comparison of strings in alphabetical order. Beginners see how Bubble Sort can be adapted for different data types, reinforcing the flexibility of the algorithm.

Program 5: Bubble Sort as a PHP Function with Callback

This advanced version allows custom comparison logic through a callback function, making the sort reusable for numbers, strings, or complex data.

<?php

function bubbleSortCallback($array, $compare) {

    $n = count($array);

    for ($i = 0; $i < $n - 1; $i++) {

        for ($j = 0; $j < $n - $i - 1; $j++) {

            if ($compare($array[$j], $array[$j + 1]) > 0) {

                $temp = $array[$j];
                $array[$j] = $array[$j + 1];
                $array[$j + 1] = $temp;

            }

        }

    }

    return $array;

}

$data = [
    ["name" => "Alice", "score" => 75],
    ["name" => "Bob", "score" => 85],
    ["name" => "Charlie", "score" => 65]
];

$sorted = bubbleSortCallback($data, function($a, $b) {
    return $a["score"] - $b["score"];
});

print_r($sorted);

?>

This version teaches beginners about abstraction and flexibility. By passing a comparison function, Bubble Sort can handle any type of data and sorting criteria.

Frequently Asked Questions (FAQ)

This section answers the most common questions beginners have about Bubble Sort in PHP.

Q1. Is Bubble Sort efficient for large datasets?
Bubble Sort is simple but not efficient for large arrays. Its time complexity is O(n²), so other algorithms like Quick Sort or Merge Sort are preferred for bigger datasets.

Q2. Can Bubble Sort handle strings?
Yes. By using functions like strcmp, Bubble Sort can sort strings alphabetically.

Q3. What is the difference between iterative and recursive Bubble Sort?
Iterative Bubble Sort uses loops, while recursive Bubble Sort calls itself on smaller portions of the array. Both achieve the same result but recursion can help understand problem decomposition.

Q4. Can we optimize Bubble Sort?
Yes. Adding a swap flag to stop early when the array is already sorted improves efficiency.

Q5. Is Bubble Sort a stable algorithm?
Yes. Bubble Sort maintains the relative order of equal elements, making it a stable sorting algorithm.

Conclusion

Bubble Sort is a fundamental algorithm that introduces beginners to sorting logic, loops, recursion, and array manipulation in PHP. While it is simple, practicing multiple implementations—from basic loops to recursion, string sorting, and flexible callback functions—gives learners a strong foundation. Understanding Bubble Sort helps beginners build confidence before moving to more advanced sorting algorithms. By experimenting with different datasets, you can truly see the versatility and principles behind this classic sorting method.

Scroll to Top