PHP algorithm heap sort

John Lennon
Release: 2023-03-23 09:46:02
Original
2382 people have browsed it

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);
Copy after login

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!

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
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!