A detailed explanation of the PHP heap and heap sequencing

Source: Internet
Author: User
Tags join

Heap Sort

Heap sorting is a sort of selection using the properties of a heap. Let's discuss the heap first.

1. Heap

The heap is actually a completely binary tree, and any one of its non-leaf nodes satisfies the nature:

KEY[I]<=KEY[2I+1]&&KEY[I]<=KEY[2I+2] or key[i]>=key[2i+1]&&key>=key[2i+2]

That is, the keyword of any non-leaf node is not greater than or not less than the key word for its left and right child nodes.

The heap is divided into large top heaps and small top heaps, satisfying the key[i]>=key[2i+1]&&key>=key[2i+2] called the large top heap, satisfying the key[i]<=key[2i+1]&&key[i]<= KEY[2I+2] is called a small top heap. By the nature of the above, the top of the heap is definitely the largest of all keywords, and the top of the heap is the smallest keyword in all the keywords.

2. Heap sort of idea

Using the large top heap (small top heap) heap top record is the feature of the maximum keyword (the minimum key), making it easy to select the maximum record (minimum record) from the disorder each time.

Its basic idea is (Big Top heap):

1 The initial sequence of key sequences to be sorted (r1,r2 ...). Rn) is constructed into a large top heap, which is the initial no zone;

2) Swap the heap top element r[1] with the last element R[n] to get the new unordered area (R1,R2,...... RN-1) and the new ordered region (RN), and satisfy the r[1,2...n-1]<=r[n];

3) Since the exchange of new heap top r[1] may violate the nature of the heap, it is necessary to the current unordered area (R1,R2,...... Rn-1) is adjusted to the new heap, and then again R[1] is exchanged with the last element of the unordered area to get the new unordered area (R1,R2 ...). Rn-2) and a new ordered region (RN-1,RN). Repeat this process until the number of elements in the ordered area is n-1, the entire sort process completes.

The operation process is as follows:

1 Initialize heap: Construct R[1..N] as heap;

2) Swap the heap top element of the current unordered area with the last record of the interval, and then adjust the new unordered area to the new heap r[1.

So for heap sequencing, the most important two operations are constructing the initial heap and adjusting the heap, in fact constructing the initial heap is actually the process of adjusting the heap, but constructing the initial heap is to adjust all the non-leaf nodes.


Heap sort and quick sort, merging sort are all the common sorts of time complexity O (N*LOGN). Before learning heap sorting, first explain what is the data structure of the two-fork heap.

The PHP heap management code is as follows:

The code is as follows Copy Code

<?php
Class heep{
static function Add (& $arr, $one) {
$arr [] = $one;
Self::up ($arr, COUNT ($arr)-1);
}
Sinking
static function del (& $arr) {
$arr [0] = Array_pop ($arr);
Self::d Own ($arr, 0,count ($arr)-1);
}
static function Swap (& $arr, $i, $p) {
$tmp = $arr [$i];
$arr [$i] = $arr [$p];
$arr [$p] = $tmp;
}
Increase the element to float
static function up (& $arr, $i) {
$p = Floor (($i-1)/2);
while ($p >= 0 && $i > 0 && $arr [$p] > $arr [$i]) {
Self::swap ($arr, $i, $p);
$i = $p;
$p = Floor (($i-1)/2);
}
}
Sinking $i start $n end
static function Down (& $arr, $i, $n) {
$l = 2* $i + 1;
while ($l <= $n) {
if ($l +1 <= $n && $arr [$l +1]< $arr [$l]) $l + +;
if ($arr [$l] > $arr [$i]) break;
Self::swap ($arr, $i, $l);
$i = $l;
$l = 2* $i + 1;
}
}
Turn an array into a heap
static function make (& $arr) {
$n = count ($arr)-1;
for ($i = $n/2-1; $i >= 0; $i-)
Self::d Own ($arr, $i, $n);
}
To sort a heap
static function sort (& $arr) {
$n = count ($arr)-1;
for ($i = $n; $i >= 0; $i-) {
Self::swap ($arr, 0, $i);
Self::d Own ($arr, 0, $i-1);
}
}
}

$arr = [10,40,30];
$arr = Array ();

Heep::add ($arr, 40);
Heep::add ($arr, 10);
Heep::add ($arr, 30);
Heep::add ($arr, 15);
Heep::add ($arr, 8);
Heep::add ($arr, 50);
Heep::add ($arr, 20);
Heep::add ($arr, 3);

echo Join (', ', $arr), ' <br> ';

Heep::d El ($arr);
Heep::d El ($arr);
Heep::d El ($arr);
echo Join (', ', $arr), ' <br> ';

Heep::sort ($arr);
echo Join (', ', $arr), ' <br> ';

$arr = [40,10,30];
Heep::make ($arr);
echo Join (', ', $arr), ' <br> ';

Assuming N is the key of the current array, the parent node of n is n>>1 or N/2 (divisible), and the left child node of n l= n<<1 or l=n*2,n the right child node r= (n<<1) +1 or r=l+1

The code is as follows Copy Code

$arr =array (1,8,7,2,3,4,6,5,9);
The original morphological structure of the array $arr is as follows:
1
/
8 7
/ /
2 3 4 6
/
5 9
Heapsort ($arr);p rint_r ($arr);
The small top heap structure that generates a standard after sorting is as follows:
1
/
2 3
/ /
4 5 6 7
/
8 9
Both arrays: Array (1,2,3,4,5,6,7,8,9):
The code is as follows:
Function Heapsort (& $arr)
{
Find the last element bit
$last =count ($arr);
$arr[0 is often ignored in heap sorting]
Array_unshift ($arr, 0);
Last Non-leaf node
$i = $last >>1;

Organize the large top heap, the largest number to the top of the heap, and the maximum number and the end of the heap, and in subsequent calculations ignore the maximum number of the back end of the array (last) until the top of the heap (last= heap top)
while (true)
{
Adjustnode ($i, $last, $arr);
if ($i >1)
{
Move the node pointer and traverse all non-leaf nodes
$i--;
}
Else
{
Critical last=1, both sorted complete
if ($last ==1) break;
When I is 1, each time the heap will get the maximum number (heap top, $arr [1]), repeat in the root node adjustment heap
Swap ($arr [$last], $arr [1]);
Keep the maximum number in size order at the end of the array and define the critical point last to avoid reordering the sorted elements after the array
$last--;
}
}
pops up the first array element
Array_shift ($arr);
}

Organize the current tree node ($n), the critical $last after the sorted elements
function Adjustnode ($n, $last,& $arr)
{
$l = $n <<1; $n's left child bit
if (!isset ($arr [$l]) | | $l > $last) return;
$r = $l +1; $n's right child bit

If the right child is larger than the left child, the parent node's right child is better than
if ($r <= $last && $arr [$r]> $arr [$l]) $l = $r;
If the child node is $n larger than the parent node, the $n is exchanged with the parent node
if ($arr [$l]> $arr [$n])
{
The value of a child node ($l) is exchanged with the value of the parent node ($n)
Swap ($arr [$l], $arr [$n]);
The value of the Swap Hofu node ($n) ($arr [$n]) may also be less than the value of the child node of the Atomic node ($l), so it is also necessary to adjust the child nodes of the Atomic node ($l), using recursion to implement the
Adjustnode ($l, $last, $arr);
}
}

Swap two values
Function swap (& $a,& $b)
{
$a = $a ^ $b;
$b = $a ^ $b;
$a = $a ^ $b;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.