I'm currently working on a project where I'm retrieving data from an API which needs to be sorted. I'm trying to use Quicksort to do the sorting, but it doesn't seem to go right. The data consists of a multidimensional array which looks like this:
[result] => Array
(
[0] => Array
(
[event_id] => 1212584488-61324fd3ad2881-14436970
[schedule_id] => 1
[start] => 2022-02-01 08:45:00
[end] => 2022-02-01 09:45:00
[title] => title
[employee_note] =>
[club_id] => XXX
[activity_id] => 322801
[instructor_id] => 0
[attendees] => 0
[max_places] => 15
[bookable] => 1
[cancel_before_duration] => 0
[booking_in_advance_duration] => 6 days
[canceled] =>
[presence_saved] =>
[language] =>
[bookable_by_third_party] =>
)
The array needs to be sorted by the start date, and my quick sort looks like this:
//Quicksort by start time
function quicksort($list, $from, $to)
{
echo $from . " " . $to . "<br></br>";
if ($from < $to) {
$pivot = $list[$to];
$i = $from;
for ($j = $from; $j <= $to; $j++) {
$comparing = $list[$j];
if (strtotime($comparing["start"]) < strtotime($pivot["start"])) {
$temp = $list[$i];
$list[$i] = $comparing;
$list[$j] = $temp;
$i++;
}
}
$temp = $list[$i];
$list[$i] = $pivot;
$list[$to] = $temp;
quicksort($list, $from, $i - 1);
quicksort($list, $i + 1, $to);
}
return $list;
}
$sortedList = quicksort($output["result"], 0, count($output["result"]) - 1);
The Quicksort generates the following output:
2022-02-01 08:45:00
2022-02-03 19:00:00
2022-02-03 20:00:00
2022-02-02 19:30:00
2022-02-04 19:30:00
2022-02-03 09:00:00
2022-02-05 09:00:00
2022-02-04 10:00:00
2022-02-05 09:45:00
2022-01-31 09:00:00
2022-02-03 10:00:00
2022-01-31 18:30:00
2022-01-31 19:30:00
2022-01-31 18:30:00
2022-01-31 20:15:00
2022-02-01 10:00:00
2022-02-01 09:00:00
2022-02-02 10:00:00
2022-02-02 09:00:00
2022-02-04 09:00:00
2022-02-01 10:00:00
2022-02-02 18:30:00
2022-02-01 19:30:00
2022-02-01 18:30:00
2022-02-01 18:30:00
2022-02-01 19:30:00
2022-02-03 18:30:00
2022-02-04 18:30:00
2022-02-02 20:30:00
2022-02-05 10:00:00
2022-02-05 11:00:00
2022-02-05 10:15:00
2022-02-06 10:00:00
2022-02-06 09:45:00
2022-02-05 10:00:00
2022-02-06 09:00:00