Graphics and text detailed heap sort heap sorting algorithm and JavaScript code implementation _ Basics

Source: Internet
Author: User
Tags arrays

1. Have to talk about the two-fork tree
to understand the heap first you have to understand the binary tree, in computer science, a binary tree is a tree structure with a maximum of two subtrees per node. Usually subtrees are called "left subtree" and "right subtree" (right-hand subtree). Binary trees are often used to implement two-fork lookup trees and two-fork heaps.
Each node of a binary tree has a maximum of two Shang trees (no node with a degree greater than 2), and the subtree of the binary tree has a left and right part, and the order cannot be reversed. The first layer of the binary tree has 2i-1 nodes at most; a two-forked tree with a depth of K has at most a 2k-1 node; for any binary tree T, if its terminal node number is n0, and the node with degree 2 is n2, then N0 = n2 + 1.
The three major differences between trees and two-pronged trees:
The number of nodes in a tree is at least 1, and the number of nodes in a binary tree can be 0.
The maximum degree of node in a tree is not limited, and the maximum degree of a binary tree node is 2.
The node of the tree has no left and right points, and the node of the binary tree has the left and right points.
The binary tree is divided into complete binary trees (complete binary tree) and two-forked trees (full binary)
Full two fork tree: a tree depth of k, and there are 2k-1 nodes called full two fork tree

(full two-binary tree with depth of 3)
Complete binary tree: A two-fork tree with a depth of K and N nodes, called a complete binary tree, if and only if each of its nodes corresponds to a node whose number is 1 to n in a two-forked tree with a depth of K

(3 full binary tree complete binary)
2. What is a heap?
the heap (binary heap) can be regarded as a complete two-forked tree, a perfectly binary tree of a "good" nature is, each layer is full except at the bottom, which allows the heap to be represented by an array (ordinary two-forked trees are usually represented by a list as a basic container), and each node corresponds to an element in the array.
The diagram below is a relationship between a heap and an array

(The correlation of heaps and arrays)
For the subscript I of a given node, it is easy to calculate the parent node of the node and the subscript of the child node:
Parent (i) = Floor (I/2), I index
Left (i) = 2i,i-sub node subscript
Right (i) = 2i + 1,i sub-node subscript

The binary heap is generally divided into two types: the maximum heap and the minimum heap.
Max Heap:
The maximum element value in the maximum heap appears at the root node (heap top).
The element value of each parent node in the heap is greater than or equal to its child node (if present)

(Max Heap)
Minimum heap:
The smallest element value in the minimum heap appears at the root node (heap top).
The element value of each parent node in the heap is less than or equal to its child node (if present)

(Minimum heap)
3. Heap sorting principle
heap sorting is to remove the maximum number of maximum heap tops, to continue to adjust the remaining heap to the maximum heap, and again to remove the maximum number of the top of the heap, which lasts until only one of the remaining numbers ends. The following actions are defined in the heap:
Max Heap Adjustment (max-heapify): Adjusts the end child nodes of the heap so that the child nodes are always smaller than the parent nodes
Create maximum heap (build-max-heap): Reorder all data in the heap so that it becomes the largest heap
Heap sort (heap-sort): Removes the root node of the first data and does the recursive operation of the maximum heap adjustment
Before continuing with the following discussion, one of the issues to be noted is that arrays are zero-based, which means that our heap data structure model is going to change

(zero-based)
Correspondingly, several calculation formulas should be adjusted accordingly:
Parent (i) = Floor ((i-1)/2), I index
Left (i) = 2i + 1,i, sub-node subscript
Right (i) = 2 (i + 1), sub-subscript of I
The maximum heap adjustment (max‐heapify) is to maintain the maximum heap nature, is to create the largest heap of the Core subroutine, the action process as shown in the figure:

(max-heapify)
Because the heap still violates the heap properties after one adjustment, a recursive test is required so that the entire heap satisfies the heap properties, which can be expressed as follows:

/**
 * Check and maintain maximum heap properties from index *
 *
 @array
 * *
 @index Check start subscript
 * *
 @heapSize Heap Size
 *
 **/< C10/>function maxheapify (array, index, heapsize) {
 var iMax = index,
   ileft = 2 * index + 1,
   iright = 2 * (i Ndex + 1);

 if (ILeft < heapsize && Array[index] < Array[ileft]) {
  iMax = ileft;
 }

 if (IRight < heapsize && Array[imax] < Array[iright]) {
  iMax = iright;
 }

 if (IMAX!= index) {
  swap (array, IMAX, index);
  Maxheapify (Array, IMax, heapsize); Recursive adjustment
 }
}

function swap (array, I, j) {
 var temp = array[i];
 Array[i] = array[j];
 ARRAY[J] = temp;
}

Generally speaking, recursion is mainly used in the division of laws, and there is no need for partition. and recursive calls need to stack/clear stack, and iterations, compared to the performance of a slight disadvantage. Of course, according to the 20/80 rule, this can be ignored. But if you think that using recursion can make your heart go through the loop, you could also use iterations, such as the following:

/**
 * Check and maintain maximum heap properties from index *
 *
 @array
 * *
 @index Check start subscript
 * *
 @heapSize Heap Size
 *
 **/< C10/>function maxheapify (array, index, heapsize) {
 var iMax, ILeft, IRight;
 while (true) {
  iMax = index;
  ILeft = 2 * index + 1;
  IRight = 2 * (index + 1);
  if (ILeft < heapsize && Array[index] < Array[ileft]) {
   iMax = ileft;
  }

  if (IRight < heapsize && Array[imax] < Array[iright]) {
   iMax = iright;
  }

  if (IMAX!= index) {
   swap (array, IMAX, index);
   index = IMax;
  } else {break
   ;
  }

}} function swap (array, I, j) {
 var temp = array[i];
 Array[i] = array[j];
 ARRAY[J] = temp;
}

The purpose of creating the maximum heap (build-max-heap) is to transform an array into a maximum heap, accept the array and heap size two parameters, build-max-heap the bottom-up call Max-heapify to transform the array, build the largest heap. Since max-heapify can ensure that the nodes of the subscript I are satisfied with the maximum heap properties, the bottom-up call Max-heapify can maintain this property during the transformation process. If the number element of the maximum heap is n, then build-max-heap starts with Parent (n) and then calls Max-heapify. The process is as follows:

Described in JavaScript are as follows:

function Buildmaxheap (array, heapsize) {
 var i,
   iparent = Math.floor ((heapSize-1)/2);
   
 for (i = iparent i >= 0; i--) {
  maxheapify (array, I, heapsize);
 }

Heap sort (heap-sort) is the interface algorithm for heap sorting, Heap-sort first call Build-max-heap to convert the array to the maximum heap, then swap the top and bottom elements of the heap, then the bottom is raised, and finally the max-heapify is kept to the maximum heap properties. Since the top element of the heap is necessarily the largest element in the heap, after one operation, the largest element in the heap is separated from the heap, and after repeated n-1, the array is arranged. The whole process is as follows:

Described in JavaScript are as follows:

function Heapsort (array, heapsize) {

 buildmaxheap (array, heapsize);

 for (int i = heapSize-1 i > 0; i--) {
  swap (array, 0, i);
  Maxheapify (array, 0, i);
 } 
}

4.JavaScript Language Implementation
Finally, put the above into the complete JavaScript code as follows:

 function Heapsort (array) {function swap (array, I, j) {var temp = array[i];
  Array[i] = Array[j];
 ARRAY[J] = temp;
  function maxheapify (array, index, heapsize) {var iMax, ileft, IRight;
   while (true) {IMax = index;
   ILeft = 2 * index + 1;

   IRight = 2 * (index + 1);
   if (ILeft < heapsize && Array[index] < Array[ileft]) {iMax = ILeft;
   } if (IRight < heapsize && Array[imax] < array[iright)) {iMax = IRight;
    if (IMAX!= index) {swap (array, IMAX, index);
   index = IMax;
   } else {break;

  }} function Buildmaxheap (array) {var i, iparent = Math.floor (ARRAY.LENGTH/2)-1;
  for (i = iparent i >= 0; i--) {maxheapify (array, I, array.length);

  } function sort (array) {buildmaxheap (array);
   for (var i = array.length-1 i > 0; i--) {swap (array, 0, i);
  Maxheapify (array, 0, i);
 } return array;
return sort (array); }

5. The application of heap sorting algorithm

(1) Algorithm performance/complexity
the time complexity of heap sorting is very stable (we can see that the input data is not sensitive), for O (n㏒n) complexity, the best scenario is the worst-case scenario.
However, the complexity of the space varies according to the implementation. Two common complexities are discussed above: O (n) and O (1). In line with the principle of space saving, I recommend O (1) Complexity method.

(2) Algorithm stability
heap sequencing has a large number of filtering and moving processes, which is an unstable sort algorithm.

(3) algorithm applicable to the scene
heap sorting produces large overhead in the process of building heaps and adjusting heaps, and does not apply when elements are small. However, in the case of more elements, it is a good choice. Especially when solving problems such as "the first n large number", it is almost the preferred algorithm.

Related Article

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.