Heap sort of PHP sorting algorithm (heap sort)

Source: Internet
Author: User
This article mainly introduced the PHP sorting algorithm heap sorting (heap sort), combined with the example form detailed analysis of the heap sequencing principle, implementation methods and related use considerations, the need for friends can refer to the following

In this article, we describe the heap sort of the PHP sorting algorithm (heap sort). Share to everyone for your reference, as follows:

Algorithm Introduction:

Here I directly quoted in the "Big talk data structure" inside the beginning:

In front of the simple selection sort, it is necessary to compare n-1 times to select a minimum record in the N records to be sorted, it is understandable that finding the first data needs to be compared so many times is normal, otherwise how to know that he is the smallest record.

Unfortunately, this kind of operation did not save the comparison of each trip, in the next trip is heavy, there are many comparisons in the previous trip has been done, but because the previous trip sort did not save these comparison results, so the next trip sort and then repeated the execution of these comparison operations, so the record more than the number of comparisons.

If you can do it every time you select to the smallest record and adjust the other records according to the comparison results, the overall efficiency of the sorting will be very high. Heap sorting is an improvement to the simple selection sort, and the effect of this improvement is very obvious.

Basic idea:

Before we introduce heap sequencing, let's start by introducing the heap:

The definition in the big talk data structure: The heap is a complete binary tree with the following properties: Each node has a value greater than or equal to the value of its left and right child nodes, and becomes a large top heap (Dagen), or the value of each node is less than or equal to the value of its left and right nodes, and becomes a small top heap (Keng Gen

At that time, I was in the view of the time there is a "heap is completely binary tree" has been questioned, the internet also said that it is not completely binary tree, but whether the heap is not a complete binary tree, still retain the opinion. We just need to know that here we use the Dagen (small heel heap) in the form of a complete binary tree, mainly for the convenience of storage and computation (which we will see later).

Heap Sorting algorithm:

Heap sequencing is the method of using heaps (assuming the large root heap) to sort, and the basic idea is to construct the sequence to be sorted into a large heap. At this point, the maximum value of the entire sequence is the root node of the heap top. Remove it (actually swap it with the end element of the heap array, at which point the element at the end is the maximum), and then reconstruct the remaining n-1 sequence into a heap, resulting in a lesser value in n elements. With this repeated execution, an ordered sequence can be obtained.

Basic operation of the Dagen sorting algorithm:

① Build The heap, build the heap is the process of constantly adjusting the heap, starting from the LEN/2 to adjust, until the first node, where Len is the number of elements in the heap. The process of building the heap is a linear process, from LEN/2 to 0 has been called to adjust the heap process, equivalent to O (H1) + O (H2) ... + O (HLEN/2) where h represents the depth of the node, LEN/2 represents the number of nodes, this is a summation process, the result is a linear O (n).

② Adjustment Heap : The tuning heap is used during the build heap and is used during the heap sequencing process. The idea is to compare node I and its child node left (i), right (i), select the maximum (or minimum) of the three, if the maximum (small) value is not node I but it's a child node, over there the interaction node I and that node, and then call the tuning heap process, which is a recursive process. The process time complexity of adjusting the heap is related to the depth of the heap, which is a LGN operation because it is adjusted along the depth direction.

③ heap Sequencing : Heap sequencing is done using the two processes above. The first is to build the heap from elements. The root node of the heap is then taken out (typically swapped with the last node), and the previous len-1 node continues the heap adjustment process before the root node is removed so that all nodes are removed. The time complexity of the heap sequencing process is O (NLGN). Because the time complexity of building the heap is O (n) (called once), the time complexity of the adjustment heap is LGN, the n-1 times are called, so the time complexity of the heap ordering is O (NLGN).

It takes a lot of graphics to see it in the process, but I'm lazy ...

Algorithm implementation:

<?php//Heap Sorting (improvements to simple selection sorting) function swap (array & $arr, $a, $b) {$temp = $arr [$a];  $arr [$a] = $arr [$b]; $arr [$b] = $temp;} Adjust the keywords $arr [$start] so that $arr[$start], $arr [$start +1] 、、、 $arr [$end] Become a large Gan (the largest full binary tree of the root node)//Note here the children of the node s are 2*s + 1 and 2*s+2  (array start subscript 0 o'clock) function heapadjust (array & $arr, $start, $end) {$temp = $arr [$start];  Next to the keyword larger child node filter down//left and right child calculation (I am here array start under identification 0)//left child 2 * $start + 1, child 2 * $start + 2 for ($j = 2 * $start + 1; $j <= $end; $j = 2 * $j + 1) {if ($j! = $end && $arr [$j] < $arr [$j + 1]) {$j + +;//Convert to right child} if ($temp >= $arr [    $j]) {break;//already satisfies the large root heap}//sets the root node to a larger value of child nodes $arr [$start] = $arr [$j];  Continue down $start = $j; } $arr [$start] = $temp;}  function Heapsort (array & $arr) {$count = count ($arr); First, the array is caused by large Gan (because it is a complete binary tree, so here with floor ($count/2)-1, subscript less than or equal to the node is the node with children) for ($i = Floor ($count/2)-1; $i >= 0; $i-) {H  Eapadjust ($arr, $i, $count); } for ($i = $count-1; $i >= 0; $i-) {//swaps the top element of the heap with the last element, gets to the largest element (the last element after the interchange), and the maximumPut the swap ($arr, 0, $i) at the end of the array;  After swapping, the last element (the largest element) is detached from the large heap and the new unsorted tree ($arr [0 ... $i-1]) is re-adjusted to Dagen heapadjust ($arr, 0, $i-1); }} $arr = Array (9,1,5,8,3,7,4,6,2); Heapsort ($arr); Var_dump ($arr);

Operation Result:

Array (9) {[0]=> int (1) [1]=> int (2) [2]=> int (3) [3]=> int (4) [4]=> int (5) [5]=> int (6) [6]=> Int (7) [7]=> Int (8) [8]=> int (9)}

Time Complexity Analysis:

It runs for as long as it is consumed in the initial build pair and in the re-screening of the rebuild heap of excrement.

In general, the time complexity of heap sequencing is O (NLOGN). Because heap sorting is not sensitive to the sort state of the original record, it is O (NLOGN), whether it is the best, worst, and average time complexity. This is obviously much better than the time complexity of bubbling, simple selection, and direct insertion of O (n^2) in performance.

Heap ordering is an unstable sort method.

This article refers to from the "Big Talk Data Structure", in this only record, convenient to consult later, great God do not spray!

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.