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

WBOY
Release: 2016-08-08 09:22:12
Original
997 people have browsed it
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;
    }
}
Copy after login

$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/>';
}
Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!