PHP Program to Implement Bucket Sort

PHP Program to Implement Bucket Sort

Bucket Sort is a fascinating sorting algorithm that works best when you have numbers distributed across a known range. Unlike other sorting algorithms that compare elements repeatedly, Bucket Sort divides the data into “buckets” based on value ranges, sorts each bucket individually, and then merges them back together. This makes it extremely efficient for certain types of datasets, especially when the numbers are spread evenly.

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

Learning Bucket Sort helps beginners understand how data can be grouped logically before sorting, which reduces unnecessary comparisons. It is often used in real-world applications like sorting floating-point numbers, grading systems, or even certain kinds of simulations where performance matters. By implementing it in PHP, you also get to practice array manipulation, loops, and functions in a very practical context.

Program 1: Basic Bucket Sort in PHP

This first program shows a straightforward implementation of Bucket Sort for integers. It divides the array into equally sized buckets, sorts each bucket using PHP’s built-in sort, and then combines the results.

<?php

$data = [29, 25, 3, 49, 9, 37, 21, 43];

function bucketSort(&$arr, $bucketSize = 5) {

    if (empty($arr)) return;

    $minValue = min($arr);
    $maxValue = max($arr);

    $bucketCount = intval(($maxValue - $minValue) / $bucketSize) + 1;
    $buckets = array_fill(0, $bucketCount, []);

    foreach ($arr as $num) {

        $index = intval(($num - $minValue) / $bucketSize);
        $buckets[$index][] = $num;

    }

    $arr = [];

    foreach ($buckets as $bucket) {

        sort($bucket);

        foreach ($bucket as $num) {
            $arr[] = $num;
        }

    }

}

bucketSort($data);

print_r($data);

?>

This version works by first determining the minimum and maximum values in the array, then distributing numbers into logical buckets. Sorting inside each bucket is simple using PHP’s sort() function. Beginners can easily understand how dividing data into groups reduces comparisons and speeds up the overall sorting process.

Program 2: Bucket Sort with Custom Sorting Function

In this variation, each bucket is sorted using a custom sorting function, which could be useful if you want to implement a different sorting strategy like insertion sort within each bucket.

<?php

$data = [42, 32, 33, 52, 37, 47, 51];

function bucketSortCustom(&$arr, $bucketSize = 5) {

    if (empty($arr)) return;

    $minValue = min($arr);
    $maxValue = max($arr);

    $bucketCount = intval(($maxValue - $minValue) / $bucketSize) + 1;
    $buckets = array_fill(0, $bucketCount, []);

    foreach ($arr as $num) {

        $index = intval(($num - $minValue) / $bucketSize);
        $buckets[$index][] = $num;

    }

    $arr = [];

    foreach ($buckets as $bucket) {

        insertionSort($bucket);

        foreach ($bucket as $num) {
            $arr[] = $num;
        }

    }

}

function insertionSort(&$bucket) {

    $size = count($bucket);

    for ($i = 1; $i < $size; $i++) {

        $key = $bucket[$i];
        $j = $i - 1;

        while ($j >= 0 && $bucket[$j] > $key) {
            $bucket[$j + 1] = $bucket[$j];
            $j--;
        }

        $bucket[$j + 1] = $key;

    }

}

bucketSortCustom($data);

print_r($data);

?>

Using a custom sorting function within each bucket allows beginners to experiment and see how different sorting strategies interact. Here, insertion sort is used, which is simple and works well for small datasets inside the buckets.

Program 3: Bucket Sort for Floating-Point Numbers

Bucket Sort shines with floating-point numbers in the range [0, 1). This version demonstrates sorting such numbers efficiently.

<?php

$data = [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23];

function bucketSortFloats(&$arr) {

    $n = count($arr);
    $buckets = array_fill(0, $n, []);

    foreach ($arr as $num) {

        $index = intval($num * $n);
        $buckets[$index][] = $num;

    }

    $arr = [];

    foreach ($buckets as $bucket) {

        sort($bucket);

        foreach ($bucket as $num) {
            $arr[] = $num;
        }

    }

}

bucketSortFloats($data);

print_r($data);

?>

By scaling the floating-point numbers into buckets, we can maintain order efficiently. Beginners will see that Bucket Sort isn’t limited to integers—it can be adapted for fractions or percentages as well.

Program 4: Bucket Sort with Step-by-Step Debug

This version prints the state of the buckets during sorting, helping learners understand how numbers are distributed and collected.

<?php

$data = [15, 42, 7, 23, 9, 31];

function bucketSortDebug(&$arr, $bucketSize = 10) {

    if (empty($arr)) return;

    $minValue = min($arr);
    $maxValue = max($arr);

    $bucketCount = intval(($maxValue - $minValue) / $bucketSize) + 1;
    $buckets = array_fill(0, $bucketCount, []);

    foreach ($arr as $num) {

        $index = intval(($num - $minValue) / $bucketSize);
        $buckets[$index][] = $num;

    }

    echo "Buckets before sorting:\n";
    print_r($buckets);

    $arr = [];

    foreach ($buckets as $bucket) {

        sort($bucket);

        foreach ($bucket as $num) {
            $arr[] = $num;
        }

    }

    echo "Array after merging buckets:\n";

    print_r($arr);

}

bucketSortDebug($data);

?>

Debugging outputs like these help beginners visualize how Bucket Sort divides the array and merges results, making the algorithm easier to grasp.

Program 5: Bucket Sort as a Reusable Utility Function

For larger projects, Bucket Sort can be wrapped in a reusable function. This approach keeps your code organized while remaining simple and self-contained.

<?php

$data = [27, 12, 45, 5, 32, 19];

function bucketSortUtil(&$arr, $bucketSize = 10) {

    if (empty($arr)) return;

    $minValue = min($arr);
    $maxValue = max($arr);

    $bucketCount = intval(($maxValue - $minValue) / $bucketSize) + 1;
    $buckets = array_fill(0, $bucketCount, []);

    foreach ($arr as $num) {

        $index = intval(($num - $minValue) / $bucketSize);
        $buckets[$index][] = $num;

    }

    $arr = [];

    foreach ($buckets as $bucket) {

        sort($bucket);

        foreach ($bucket as $num) {
            $arr[] = $num;
        }

    }

}

bucketSortUtil($data);

print_r($data);

?>

Wrapping Bucket Sort in a function demonstrates how sorting logic can be reused anywhere in your codebase, which is a key skill for PHP developers as projects grow.

Program 6: Bucket Sort Handling Negative Numbers

This program shows how to modify Bucket Sort to correctly sort arrays containing both positive and negative numbers. It adjusts the bucket calculations so negative values are placed properly.

<?php

function bucketSortWithNegatives(&$arr) {

    if (count($arr) == 0) return;

    // Find min and max values
    $min = min($arr);
    $max = max($arr);
    $range = $max - $min + 1;

    $bucketCount = count($arr);
    $buckets = array_fill(0, $bucketCount, []);

    // Place elements into buckets, adjusting for negative numbers
    foreach ($arr as $num) {

        $index = intval(($num - $min) * ($bucketCount - 1) / $range);
        $buckets[$index][] = $num;

    }

    // Sort each bucket and concatenate
    $arr = [];

    foreach ($buckets as $bucket) {

        sort($bucket); // You can replace with any sorting algorithm

        foreach ($bucket as $num) {
            $arr[] = $num;
        }

    }

}

// Example usage
$list = [3, -2, 7, -5, 0, 12, -1];

bucketSortWithNegatives($list);

print_r($list);

?>

This version works by first finding the minimum and maximum values and then mapping every number into a bucket based on its relative position in the range. Negative numbers are automatically handled because the formula subtracts the minimum value, shifting all numbers into a positive range for indexing. Beginners can see how small tweaks to formulas allow the algorithm to handle a wider variety of input safely and efficiently.

Frequently Asked Questions (FAQ)

Bucket Sort often raises questions for beginners. Here are some common ones:

Q1. Can Bucket Sort work with negative numbers?
Yes, but you need to adjust bucket calculations to accommodate negative ranges.

Q2. When is Bucket Sort better than Quick Sort or Merge Sort?
It is ideal when data is uniformly distributed over a known range and when you can avoid many comparisons.

Q3. Does Bucket Sort work for non-numeric data?
It can, if you define a way to map data into numerical buckets, such as characters or grades.

Q4. What is the time complexity of Bucket Sort?
On average, it is O(n + k), where n is the number of elements and k is the number of buckets.

Q5. Is Bucket Sort stable?
Yes, if the internal sorting within buckets preserves the order of equal elements.

Conclusion

Bucket Sort is an elegant algorithm that introduces the idea of grouping data before sorting. Beginners can learn how breaking data into manageable sections can make sorting more efficient. By practicing with PHP, you also strengthen skills in arrays, loops, and reusable functions. With the examples above, you now have multiple ways to implement and understand Bucket Sort—from basic integer arrays to floating-point numbers, debugging outputs, and reusable functions. Practicing these techniques will help build a solid foundation for tackling more advanced sorting challenges in PHP.

Scroll to Top