您好,欢迎访问一九零五行业门户网

PHP实现堆排序算法(代码示例)

在计算机科学中,heapsort(1964年由j. w. j. williams发明)是一种基于比较的排序算法。heapsort(堆排序)可以看作是一种改进的选择排序:与该算法类似,它将输入分为已排序区域和未排序区域,并通过提取最大的元素并将其移动到已排序区域来交互式地缩小未排序区域。改进包括使用堆数据结构,而不是线性时间搜索来找到最大值。
尽管在大多数机器上,它的实际运行速度比实现良好的快速排序要慢一些,但它的优势是在最坏情况下o(n log n)运行时更有利。堆排序是一种就地排序算法,但它不是一种稳定排序。
heapsort算法对一组随机排列的值进行排序。在算法的第一阶段,数组元素被重新排序以满足堆属性。在进行实际排序之前,将简要展示堆树结构以供说明。
php堆排序算法思路示意图:
php堆排序实现代码如下:
<?phpclass node{ private $_i; public function __construct($key) { $this->_i = $key; } public function getkey() { return $this->_i; }}class heap{ private $heap_array; private $_current_size; public function __construct() { $heap_array = array(); $this->_current_size = 0; } public function remove() { $root = $this->heap_array[0]; $this->heap_array[0] = $this->heap_array[--$this->_current_size]; $this->bubbledown(0); return $root; } public function bubbledown($index) { $larger_child = null; $top = $this->heap_array[$index]; while ($index < (int)($this->_current_size/2)) { $leftchild = 2 * $index + 1; $rightchild = $leftchild + 1; if ($rightchild < $this->_current_size && $this->heap_array[$leftchild] < $this->heap_array[$rightchild]) { $larger_child = $rightchild; } else { $larger_child = $leftchild; } if ($top->getkey() >= $this->heap_array[$larger_child]->getkey()) { break; } $this->heap_array[$index] = $this->heap_array[$larger_child]; $index = $larger_child; } $this->heap_array[$index] = $top; } public function insertat($index, node $newnode) { $this->heap_array[$index] = $newnode; } public function incrementsize() { $this->_current_size++; } public function getsize() { return $this->_current_size; } public function asarray() { $arr = array(); for ($j = 0; $j < sizeof($this->heap_array); $j++) { $arr[] = $this->heap_array[$j]->getkey(); } return $arr; }}function heapsort(heap $heap){ $size = $heap->getsize(); for ($j = (int)($size/2) - 1; $j >= 0; $j--) { $heap->bubbledown($j); } for ($j = $size-1; $j >= 0; $j--) { $biggestnode = $heap->remove(); $heap->insertat($j, $biggestnode); } return $heap->asarray();}$arr = array(3, 0, 2, 5, -1, 4, 1);echo "原始数组 : ";echo implode(', ',$arr );$heap = new heap();foreach ($arr as $key => $val) { $node = new node($val); $heap->insertat($key, $node); $heap->incrementsize();}$result = heapsort($heap);echo "\n排序后数组 : ";echo implode(', ',$result)."\n";
输出:
原始数组 : 3, 0, 2, 5, -1, 4, 1 排序后数组 : -1, 0, 1, 2, 3, 4, 5
本篇文章就是关于php堆排序的介绍,希望对需要的朋友有所帮助!
以上就是php实现堆排序算法(代码示例)的详细内容。
其它类似信息

推荐信息