Home  >  Article  >  Backend Development  >  Detailed explanation of how to implement heap sorting in PHP

Detailed explanation of how to implement heap sorting in PHP

黄舟
黄舟Original
2017-03-17 09:57:301543browse

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) kic4a94c3c4c1cb4e3c4beab8b8a55641f= 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); //继续调整剩余元素为大根堆
	}
}

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!

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