堆排序也就这么点代码(PHP实现)

代码:

<?php

function heap_sort($arr = []){
	adjust_heap($arr); // 初始化调整堆

	$tmp_arr = [];

	while(!empty($arr)){
		$tmp_arr[] = array_shift($arr);

		adjust_heap($arr);
	}

	return $tmp_arr;
}

function adjust_heap(&$arr = []){
	$arr_len = count($arr);
	$parent_index = intval($arr_len/2)-1;

	while ($parent_index > -1) {
		$left_child_index = (2 * $parent_index) + 1; // 至少存在左子树
		$right_child_index = (2 * $parent_index) + 2;

		$winner_index = $left_child_index;
		
		// 注意比较运算法 <
		if(!empty($arr[$right_child_index]) && ($arr[$right_child_index] < $arr[$left_child_index])){
			$winner_index = $right_child_index;
		}

		if ($arr[$parent_index] > $arr[$winner_index]) {
			$tmp = $arr[$parent_index];
			$arr[$parent_index] = $arr[$winner_index];
			$arr[$winner_index] = $tmp;
		}

		$parent_index--;
	}
}

// $arr = [3, 2, 8];
// $arr = [2, 13, 1, 5, 99, 234, 23, 33];
$arr = [3, 34, 443, 123, 2, 1, 543, 534234, 19, 234,9434];

$arr = heap_sort($arr);

print_r($arr);

输出:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 19
    [4] => 34
    [5] => 123
    [6] => 234
    [7] => 443
    [8] => 543
    [9] => 9434
    [10] => 534234
)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值