2022-07-23 23:37:36 -06:00
|
|
|
<?php
|
2023-10-04 21:36:11 +03:30
|
|
|
|
2022-07-23 23:37:36 -06:00
|
|
|
/**
|
|
|
|
* 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
|
2023-10-06 14:51:11 +02:00
|
|
|
if (empty($input)) {
|
2022-07-23 23:37:36 -06:00
|
|
|
return [];
|
|
|
|
}
|
|
|
|
|
|
|
|
$lt = [];
|
|
|
|
$gt = [];
|
2023-10-04 21:36:11 +03:30
|
|
|
if (sizeof($input) < 2) {
|
2022-07-23 23:37:36 -06:00
|
|
|
return $input;
|
|
|
|
}
|
|
|
|
|
|
|
|
$key = key($input);
|
|
|
|
$shift = array_shift($input);
|
2023-10-04 21:36:11 +03:30
|
|
|
foreach ($input as $value) {
|
2022-07-23 23:37:36 -06:00
|
|
|
$value <= $shift ? $lt[] = $value : $gt[] = $value;
|
|
|
|
}
|
|
|
|
|
|
|
|
return array_merge(quickSort($lt), [$key => $shift], quickSort($gt));
|
|
|
|
}
|