-
-
Notifications
You must be signed in to change notification settings - Fork 566
Expand file tree
/
Copy pathQuickSort.php
More file actions
30 lines (26 loc) · 667 Bytes
/
QuickSort.php
File metadata and controls
30 lines (26 loc) · 667 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
/**
* Quick Sort
* Compare number in an array to the next number and sets to new array (greater than or less than)
*
* @param array $input array of random numbers
* @return array sorted array of numbers
*/
function quickSort(array $input)
{
// Return nothing if input is empty
if (empty($input)) {
return [];
}
$lt = [];
$gt = [];
if (sizeof($input) < 2) {
return $input;
}
$key = key($input);
$shift = array_shift($input);
foreach ($input as $value) {
$value <= $shift ? $lt[] = $value : $gt[] = $value;
}
return array_merge(quickSort($lt), [$key => $shift], quickSort($gt));
}