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,
--
Rowan Collins
[IMSoP]
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php