Le 08/03/2015 19:05, Rowan Collins a écrit :
On 08/03/2015 15:45, Grégory Planchat wrote:
class BarSortable implements Sorter
{
public function sort(Sortable $collection)
{
$previousKey = null;
$previousElement = null;
foreach ($collection as $key => $element) {
if ($previousKey === null) {
$previousKey = $key;
$previousElement = $element;
continue;
}
if ($previousElement < element) {
$collection->swap($previousKey, $key);
}
$previousKey = $key;
$previousElement = $element;
}
}
}
Unfortunately, this won't actually sort the array - it only makes one
check of each value, so [4, 1, 2, 3, 5] would come out as [4, 2, 3, 1,
5], when it should be [5, 4, 3, 2, 1] (your < sign means you're sorting
largest value first). It's *almost* like a bubble sort, though (you keep
swapping things until you know that there's no more swaps to be made),
which is the simplest but also least efficient way of sorting a list.
I think insertion sort, which is simple and efficient for small lists,
could be done with iteration plus a single callback of
"insertElementAt". For larger lists, though, you're going to want a
quicksort, and I can't quite picture what callbacks that would need to
run on the collection as it went; it ultimately requires some way of
partitioning the list into multiple pieces.
Regards,
Yes you're right, I wrote up this example a bit too fast, with lots of
mistakes. I since went over my proposal and fixed them.
It is in fact a bit too large for sending it on internals@ and related
to another proposal I made here, so I wrote it on a github repository
and merged it with the other proposal:
https://github.com/gplanchat/php-oop-api/blob/master/doc/sorting.md
I think this implementation is a bit more solid.
The point made after the SortableAggregate and SorterAggregate is that a
userland class may encapsulate the real collection. Instead of making
decorators over and over again - which would be a performance hurdle - I
brought the idea of passing the real sorter via a visitor pattern.
I thought of this implementation to find a solution for OO API with
arrays, as you can read here:
https://github.com/gplanchat/php-oop-api/blob/master/doc/array.md
https://github.com/gplanchat/php-oop-api/blob/master/doc/array-sorter.md
Grégory Planchat
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php