You can use priority queue to find min from k elements at any time in O(logk). Total number of lookups will be n * k, so the running time is O(n*k*logk). PHP already has SplPriorityQueue which is implemented using heap:
$p2) return -1;
return 0;
}
}
$arrays = array(
0 => array(1, 5, 8, 9, 10, 15),
1 => array(-5, 6, 6, 7, 9, 90, 111),
2 => array(-5, 6, 6, 7, 9, 90, 111),
3 => array(9999),
);
$n = count($arrays);
$indices = array();
$queue = new MinPriorityQueue;
for ($i = 0; $i insert($i, $arrays[$i][0]);
$indices[$i] = 0;
}
$result = array();
while (!$queue->isEmpty()) {
$index = $queue->extract();
$result[] = $arrays[$index][$indices[$index]++];
if (isset($arrays[$index][$indices[$index]])) {
$queue->insert($index, $arrays[$index][$indices[$index]]);
}
}
print_r($result);