Home >Backend Development >PHP Tutorial >PHP uses the SPL standard library to obtain the smallest K values ​​in the array

PHP uses the SPL standard library to obtain the smallest K values ​​in the array

WBOY
WBOYOriginal
2016-08-08 09:22:121073browse
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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn