Skip to content

Commit e4e2c63

Browse files
committed
Counting sort with PHP tested with PHPunit
1 parent cce1c8a commit e4e2c63

2 files changed

Lines changed: 66 additions & 0 deletions

File tree

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php
2+
/**
3+
* Counting Sort Algirithm
4+
*
5+
* @param Array $array The original array
6+
* @return Array $order The order array
7+
*/
8+
function counting_sort($array = []){
9+
// Return [] if the array has no elements
10+
if( !is_array($array) || !count($array) ){
11+
return $array;
12+
}
13+
14+
// Find the min and max value
15+
$max = max($array);
16+
$min = min($array);
17+
18+
// Fill the aux array from min to max with 0
19+
$aux = [];
20+
$aux = array_fill($min, $max, 0);
21+
22+
foreach($array as $element){
23+
$aux[$element]++;
24+
}
25+
26+
// Fill the order array
27+
$order = [];
28+
foreach($aux as $key => $value){
29+
$i = 0;
30+
while($i++ < $value){
31+
array_push($order, $key);
32+
}
33+
}
34+
return $order;
35+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
3+
require 'counting_sort.php';
4+
5+
class CountingSortTest extends PHPUnit_Framework_TestCase{
6+
7+
public function testNoParameters(){
8+
$this->assertEmpty(counting_sort([]));
9+
}
10+
11+
public function testArrayWithUnorderElements(){
12+
$original = [3,5,7,1,5,1,2,3,2,71,2,3,4,71,47,7];
13+
$copy = [3,5,7,1,5,1,2,3,2,71,2,3,4,71,47,7];
14+
sort($copy, SORT_NUMERIC);
15+
16+
$this->assertEquals(counting_sort($original), $copy);
17+
}
18+
19+
public function testArrayWithOrderelements(){
20+
$original = [0,1,2,3,4,5,6,7,8,9,10];
21+
$copy = [0,1,2,3,4,5,6,7,8,9,10];
22+
23+
$this->assertEquals(counting_sort($original), $copy);
24+
}
25+
26+
public function testArrayWithRepeatedElements(){
27+
$original = [1,1,1,1,1,1,1,1,1,1,1];
28+
$copy = [1,1,1,1,1,1,1,1,1,1,1];
29+
$this->assertEquals(counting_sort($original), $copy);
30+
}
31+
}

0 commit comments

Comments
 (0)