Home>Article>Backend Development> PHP algorithm heap sort

PHP algorithm heap sort

不言
不言 Original
2018-04-08 13:15:20 2381browse

The content introduced in this article is the code of heap sorting in the PHP algorithm. Now I share it with you. Friends in need can also refer to it. Let’s take a look together.

= $arr[$j]){ break; //已经满足大根堆 } //将根节点设置为子节点的较大值 $arr[$start] = $arr[$j]; //继续往下 $start = $j; } $arr[$start] = $temp; } function HeapSort(array &$arr){ $count = count($arr); //先将数组构造成大根堆(由于是完全二叉树,所以这里用floor($count/2)-1,下标小于或等于这数的节点都是有孩子的节点) for($i = floor($count / 2) - 1;$i >= 0;$i --){ HeapAdjust($arr,$i,$count); } for($i = $count - 1;$i >= 0;$i --){ //将堆顶元素与最后一个元素交换,获取到最大元素(交换后的最后一个元素),将最大元素放到数组末尾 swap($arr,0,$i); //经过交换,将最后一个元素(最大元素)脱离大根堆,并将未经排序的新树($arr[0...$i-1])重新调整为大根堆 HeapAdjust($arr,0,$i - 1); } } $arr = array(4,1,5,9); HeapSort($arr); var_dump($arr);

Related recommendations:

php algorithm quick sort

PHP algorithm bucket sort

The above is the detailed content of PHP algorithm heap sort. For more information, please follow other related articles on the PHP Chinese website!

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
Previous article:PHP algorithm quick sort Next article:PHP algorithm quick sort