Detailed explanation of how to implement heap sorting in PHP

黄舟
Release: 2023-03-06 17:48:02
Original
1575 people have browsed it

Definition of heap:

#n keyword sequences Kl, K2,...,Kn are called (Heap) if and only if This sequence satisfies the following properties (heap properties for short): (1) ki<=k(2i) and ki<=k(2i+1)(1≤i≤n/2). Of course, this is a small root heap, The big root heap is replaced with the >= sign. k(i) is equivalent to the non-leaf node of the binary tree, K(2i) is the left child node, and k(2i+1) is the right child node. If the vector R[1..n] stored in this sequence is regarded as the storage structure of a complete binary tree, then the heap is essentially a complete binary tree that satisfies the following properties: the key of any non-leaf node in the tree is A keyword that is not greater than (or not less than) its left and right child nodes (if they exist).

/**
 * 调整堆
 * @param array $arr	排序数组
 * @param int $i    	待调节元素的下标
 * @param int $size 	数组大小, 准确来说是数组最大索引值加1
 */
function heapAjust(& $arr, $i, $size)
{
	$key = $arr[$i];
	// 索引从0开始
	// 左孩子节点为 2i+1, 右孩子节点为 2i+2
	for($j = 2 * $i + 1; $j < $size; $j = 2 * $j + 1) {
		if($j + 1 < $size && $arr[$j] < $arr[$j + 1])
			$j++;
		if($key > $arr[$j])
			break ;
		$arr[$i] = $arr[$j]; //调换值
		$i = $j;
	}
	$arr[$i] = $key;
}

/**
 * 堆排序
 * 时间复杂度:O(nlogn)
 * 不稳定的排序算法
 */
function heapSort(& $arr)
{
	$len = count($arr);
	
	// 构建初始大根堆
	for($i = intval($len/2); $i >= 0; $i--) {
		heapAjust($arr, $i, $len);
	}

	// 调换堆顶元素和最后一个元素
	for($j = $len - 1; $j > 0; $j--) {
		$swap = $arr[0];
		$arr[0] = $arr[$j];
		$arr[$j] = $swap;
		heapAjust($arr, 0, $j); //继续调整剩余元素为大根堆
	}
}
Copy after login

The above is the detailed content of Detailed explanation of how to implement heap sorting in PHP. 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
Popular Tutorials
More>
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!