PHP 利用SPL標準庫獲取數組中最小的K個值

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/>';
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章