Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/BucketSort.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace Src;

class BucketSort
{
private static string $sortingAlgorithm = "Src\\Gnomesort";

/**
* @param array<int, int|float> $arr
* @return array<int, int|float>
*/
public static function sort(array $arr): array
{
$length = count($arr);
if ($length == 0 || $min= min($arr) == $max = max($arr)) {
return $arr;
}
$range = $max - $min;
$bucketSize = (int)sqrt($length);
$buckets = [];
foreach ($arr as $element) {
$index = (($element - $min) / $range) * ($bucketSize - 1);
$buckets[(int)$index][] = $element;
}
for ($i = 0; $i<$bucketSize; $i++) {
$buckets[$i] = self::$sortingAlgorithm::sort($buckets[$i]);
}
$result = [];
for($i = 0; $i<$bucketSize; $i++) {
$result = array_merge($result, $buckets[$i]);
}
return $result;
}
}
60 changes: 60 additions & 0 deletions tests/BucketSortTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

declare(strict_types=1);

use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use Src\BucketSort;

final class BucketSortTest extends TestCase
{
#[Test]
#[DataProvider('arrayProvider')]
public function it_should_return_the_sorted_array($arr)
{
$this->assertEquals([1,2,3,4,5,6,7,8,9], BucketSort::sort($arr));
}

/*
* @return array
*/
public static function arrayProvider(): array
{
return [
[[1,2,3,4,5,6,7,8,9]],
[[9,8,7,6,5,4,3,2,1]],
[[1,2,3,9,8,7,6,5,4]],
[[9,8,7,1,2,3,4,5,6]],
[[9,1,8,2,7,3,6,4,5]],
[[1,9,2,8,3,7,4,6,5]],
[[6,4,1,8,3,9,2,5,7]],
];
}

#[Test]
public function it_should_sort_single_element_array()
{
$this->assertEquals([4], BucketSort::sort([4]));
}

#[Test]
public function test_empty_array()
{
$this->assertEquals([], BucketSort::sort([]));
}

#[Test]
public function it_should_sort_non_consecutive_numbers_correctly()
{
$this->assertEquals([2,5,6,8,9], BucketSort::sort([5,9,6,2,8]));
}

#[Test]
public function it_can_sort_array_with_1000_elements()
{
$random = range(1, 1000);
shuffle($random);
$this->assertEquals(range(1, 1000), BucketSort::sort($random));
}
}
Loading