php實現堆排序

來源:互聯網
上載者:User

標籤:

 1 abstract class Heap { 2     protected $elements = array(); 3     protected $n = 0; 4      5     public abstract function insert($element); 6  7     public function isEmpty() { 8         return $this->n==0; 9     }10     11     public function all(){12         return $this->elements;13     }14 15     /**16      * Extract the top value of the heap17      *18     */19     public function extract() {20         $element = $this->elements[1];21         $this->elements[1] = array_pop($this->elements);22         $this->n--;23         $this->siftDown();24         return $element;25     }26     27     /**28      * Rearranges the heap after an extraction to keep the heap property29      */30     protected abstract function siftDown();31 32     /**33      * Swap two elements on the elements array34      *35      */36     protected function swap($x,$y) {37         $tmp = $this->elements[$x];38         $this->elements[$x] = $this->elements[$y];39         $this->elements[$y] = $tmp;40     }41 }42 class MinHeap extends Heap {43     44     public function insert($element) {45         $this->elements[++$this->n] = $element;46         for ($i = $this->n; $i > 1 && $this->elements[$i >> 1] > $this->elements[$i]; $i = $i >> 1)47             $this->swap($i >> 1,$i);48     }49     protected function siftDown() {50         for ($i = 1; ($c = $i * 2) <= $this->n; $i = $c) {51             //Checks which of the smaller child to compare with the parent52             if ($c+1 <= $this->n && $this->elements[$c+1] < $this->elements[$c])53                 $c++;54             if ($this->elements[$i] < $this->elements[$c])55                 break;56             $this->swap($c, $i);57         }58     }59 60 }61 62 function heapSort($array){63     $heap=new MinHeap();64     foreach($array as $val){65         $heap->insert($val);66         67     }    68     $arr=array();69     while(!$heap->isEmpty()){70         $arr[]=$heap->extract();71     }    72     return $arr;73 }74 $array=array(1,13,8,4,5);75 $arr=heapSort($array);76 print_r($arr);

 

php實現堆排序

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.