forked from kennyledet/Algorithm-Implementations
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquicksort.php
More file actions
30 lines (26 loc) · 785 Bytes
/
Copy pathquicksort.php
File metadata and controls
30 lines (26 loc) · 785 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php
/**
* QuickSort Algorithm for order elements inside of an array
*
* @params Array $array The array to order
* @return Array The order array
*/
function quicksort($array = []){
$length = count($array) - 1;
if($length < 1){
return $array;
}
$index = $length / 2;
$pivot = $array[$index];
// Remove element from the array
unset($array[$index]);
$less = [] ;
$greater = [];
// Loop over the whole array
foreach($array as $element){
($element <= $pivot) ? array_push($less, $element) : array_push($greater, $element);
}
// Merge the whole array as a recursive call to the
// two arrays: $less and $greater
return array_merge( quicksort($less), [$pivot], quicksort($greater) );
}