diff --git a/src/BucketSort.php b/src/BucketSort.php new file mode 100644 index 0000000..e8c9c4e --- /dev/null +++ b/src/BucketSort.php @@ -0,0 +1,35 @@ + $arr + * @return array + */ + 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; + } +} diff --git a/tests/BucketSortTest.php b/tests/BucketSortTest.php new file mode 100644 index 0000000..eb57bfb --- /dev/null +++ b/tests/BucketSortTest.php @@ -0,0 +1,60 @@ +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)); + } +}