PHP implementation heap Sequencing, PHP heap sequencing
For the concept of heap sequencing own Baidu to go, today it's okay. Algorithm for heap sorting using PHP
1 Abstract classHeap {2 protected $elements=Array();3 protected $n= 0;4 5 Public Abstract functionInsert$element);6 7 Public functionIsEmpty () {8 return $this->n==0;9 }Ten One Public functionAll () { A return $this-elements; - } - the /** - * Extract The top value of the heap - * - */ + Public function Extract() { - $element=$this->elements[1]; + $this->ELEMENTS[1] =Array_pop($this-elements); A $this->n--; at $this-Siftdown (); - return $element; - } - - /** - * Rearranges the heap after a extraction to keep the heap in */ - protected Abstract functionSiftdown (); to + /** - * Swap elements on the elements array the * * */ $ protected functionSwap$x,$y) {Panax Notoginseng $tmp=$this->elements[$x]; - $this->elements[$x] =$this->elements[$y]; the $this->elements[$y] =$tmp; + } A } the classMinheapextendsHeap { + - Public functionInsert$element) { $ $this->elements[++$this->n] =$element; $ for($i=$this->n;$i> 1 &&$this->elements[$i>> 1] >$this->elements[$i];$i=$i>> 1) - $this->swap ($i>> 1,$i); - } the protected functionSiftdown () { - for($i= 1; ($c=$i* 2) <=$this->n;$i=$c) {Wuyi //Checks which of the smaller child to compare with the parent the if($c+1 <=$this->n &&$this->elements[$c+1] <$this->elements[$c]) - $c++; Wu if($this->elements[$i] <$this->elements[$c]) - Break; About $this->swap ($c,$i); $ } - } - - } A + functionHeapsort ($array){ the $heap=Newminheap (); - foreach($array as $val){ $ $heap->insert ($val); the the } the $arr=Array(); the while(!$heap-IsEmpty ()) { - $arr[]=$heap-Extract(); in } the return $arr; the } About $array=Array(1,13,8,4,5); the $arr=heapsort ($array); the Print_r($arr);
http://www.bkjia.com/PHPjc/975481.html www.bkjia.com true http://www.bkjia.com/PHPjc/975481.html techarticle PHP Implementation heap sorting, PHP heap sorting for the concept of heap sequencing own Baidu to go, today it's okay to use PHP to implement heap sorting algorithm 1 abstract class Heap {2 protected $elements = Array ();