I'm wondering which approach is the best with writing sorting algorithms, which sort-in-place (does not require additional space and sort an array it is given without copying it). Such examples are Insertion Sort, Quick Sort and others.
So far most of the examples I encounter in github are following:
//...
public function sort(array $array): array
{
//...
return $array;
}
Isn't it not the most efficient way of writing this down in php? What I mean is that it loses completely all the 'in-place' benefits. It copies the array each time it is passed to the function and returns yet again a copied array.
Wouldn't it be better to use
//...
public function sort(array &$array): void
{
//...
}
approach? So that we don't have any unnecessary copying and really sort things in-place. If we check memory_get_peak_usage()
values it shows that the latter (with the reference &) is almost twice lower than the first method.
I know references are not really 'best practice' in many cases and frowned upon, but here it seems they do really have their fair place, don't they?