Skip to content

Commit b8bc9a9

Browse files
committed
Quick Sort With PHP, tested with PHPUnitTest
1 parent 77e078d commit b8bc9a9

2 files changed

Lines changed: 63 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
/**
3+
* QuickSort Algorithm for order elements inside of an array
4+
*
5+
* @params Array $array The array to order
6+
* @return Array The order array
7+
*/
8+
function quicksort($array = []){
9+
$length = count($array) - 1;
10+
11+
if($length < 1){
12+
return $array;
13+
}
14+
$index = $length / 2;
15+
$pivot = $array[$index];
16+
// Remove element from the array
17+
unset($array[$index]);
18+
19+
$less = [] ;
20+
$greater = [];
21+
22+
// Loop over the whole array
23+
foreach($array as $element){
24+
($element <= $pivot) ? array_push($less, $element) : array_push($greater, $element);
25+
}
26+
27+
// Merge the whole array as a recursive call to the
28+
// two arrays: $less and $greater
29+
return array_merge( quicksort($less), [$pivot], quicksort($greater) );
30+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<?php
2+
require 'quicksort.php';
3+
4+
class QuickSortTest extends PHPUnit_Framework_TestCase{
5+
6+
public function testWithArrayEmpty(){
7+
$this->assertEmpty(quicksort([]));
8+
}
9+
10+
public function testArrayWithUnorderElements(){
11+
$original = [12321,43535,2342423,4364576,2343323,3534534,212,1,2,0,234234,234,34];
12+
$copy = [12321,43535,2342423,4364576,2343323,3534534,212,1,2,0,234234,234,34];
13+
// Order the array copy
14+
sort($copy,SORT_NUMERIC);
15+
16+
$this->assertEquals(quicksort($original), $copy);
17+
}
18+
19+
public function testArrayWithOrderElements(){
20+
$original = [1,2,3,4,5,6,7,8,9];
21+
$copy = [1,2,3,4,5,6,7,8,9];
22+
$this->assertEquals(quicksort($original), $copy);
23+
}
24+
25+
public function testArrayWithOrderElementsReverOrder(){
26+
$original = [9,8,7,6,5,4,3,2,1];
27+
$copy = [9,8,7,6,5,4,3,2,1];
28+
// Order the array copy
29+
sort($copy,SORT_NUMERIC);
30+
31+
$this->assertEquals(quicksort($original), $copy);
32+
}
33+
}

0 commit comments

Comments
 (0)