Exemplo n.º 1
0
/**
 * Merge an array of arrays so that the result is in sorted order.
 *
 * @param array $arrays
 * @return array
 */
function mergeSortedArrays(array $arrays)
{
    if (empty($arrays)) {
        return [];
    }
    $heads = array_fill(0, count($arrays), 0);
    $minHeap = new \SplMinHeap();
    $result = [];
    // Insert the first value from each sorted array into the min heap
    for ($i = 0; $i < count($arrays); $i++) {
        if (!empty($arrays[$i])) {
            $minHeap->insert([$arrays[$i][0], $i]);
            $heads[$i] = 1;
        }
    }
    while (!$minHeap->isEmpty()) {
        $smallestArray = $arrays[$minHeap->top()[1]];
        $smallestHead = $heads[$minHeap->top()[1]];
        $result[] = $minHeap->top()[0];
        // If the smallest array has more values, put the next one into the heap
        if ($smallestHead < count($smallestArray)) {
            $minHeap->insert([$smallestArray[$smallestHead], $minHeap->top()[1]]);
            $heads[$minHeap->top()[1]] += 1;
        }
        $minHeap->extract();
    }
    return $result;
}
Exemplo n.º 2
0
<?php

$pq = new SplMinHeap();
$pq->insert(array(3, 'Clear drains'));
$pq->insert(array(4, 'Feed cat'));
$pq->insert(array(5, 'Make tea'));
$pq->insert(array(1, 'Solve RC tasks'));
$pq->insert(array(2, 'Tax return'));
while (!$pq->isEmpty()) {
    print_r($pq->extract());
}