class MaxHeap extends SplHeap{ public function compare($value1, $value2) { return ($value1 - $value2); } public function GetKMinNum($arr, $k){ if(is_array($arr) && $k > 0){ $count = count($arr); for($i=0; $i<$count; $i++){ if($i < $k){ $this->insert($arr[$i]); }else{ $top = $this->top(); if($top > $arr[$i]){ $this->extract(); $this->insert($arr[$i]); } } } } return $this; } }
$heap = new MaxHeap(); $arr = array(); for($i=0; $i<100000; $i++){ $arr[] = rand(100, 1000000); } $min = $heap->GetKMinNum($arr, 7); foreach($min as $val){ echo $val . '<br/>'; }
The above introduces PHP's use of the SPL standard library to obtain the smallest K values in an array, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.