Heap Sort heap Sorting Algorithm and JavaScript code implementation, Heap heap sorting

Source: Internet
Author: User

Heap Sort heap Sorting Algorithm and JavaScript code implementation, Heap heap sorting

1. I have to talk about Binary Trees.
To understand the heap, you must first understand the binary tree. in computer science, a binary tree is a tree structure with a maximum of two Subtrees on each node. Generally, a subtree is called "left subtree" and "right subtree ). Binary Tree is often used to implement binary search tree and binary heap.
Each node of a binary tree has at most two Subtrees (nodes with no degree of presence greater than 2). the Subtrees of a binary tree have left and right points, and the order cannot be reversed. The I layer of a binary tree has at most 2i-1 nodes. A k-depth binary tree has at most 2 k-1 nodes. For any binary tree T, if the terminal node number is n0 and the node number of degree 2 is n2, n0 = n2 + 1.
There are three major differences between trees and binary trees:
The number of nodes in a tree must be at least 1, and the number of nodes in a binary tree can be 0.
The maximum number of nodes in the tree is unlimited, while the maximum number of nodes in the binary tree is 2.
Tree nodes have no left or right, while Tree nodes have left or right
Binary Trees are divided into complete binary Trees and full binary Trees)
Full Binary Tree: the depth of a tree is k, and 2 k-1 node is called full binary tree.

(Full binary tree with a depth of 3)
Full Binary Tree: a binary tree with a depth of k and n nodes. if and only when each of its nodes is paired with a node with a full binary tree with a depth of k, it is called a Complete Binary Tree.

(Complete binary tree with a depth of 3)
2. What is heap?
A heap (Binary heap) can be regarded as a complete binary tree. A "excellent" nature of a Complete Binary Tree is that each layer is full except for the bottom layer, this allows the heap to be represented by arrays (Common Binary Trees are usually represented by linked lists as basic containers). Each node corresponds to an element in the array.
For example, the relationship between a heap and an array

(Relationship between heap and array)
For the subscript I of a given node, it is easy to calculate the subscript of the parent node and child node of this node:
Parent (I) = floor (I/2), subscripts of the Parent node of I
Left (I) = 2i, subscript of the Left subnode of I
Right (I) = 2i + 1, subscript of the Right subnode of I

Binary heap is generally divided into two types: Maximum heap and 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 that of its child node (if any)

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

(Minimum heap)
3. Heap sorting principle
Heap sorting is to extract the maximum number of heap top, adjust the remaining heap to the maximum number, and then retrieve the maximum number of heap top again, this process continues until there is only one remaining number. Define the following operations in the heap:
Max-Heapify: adjusts the terminal node of the heap so that the child node is always smaller than the parent node.
Build-Max-Heap: sorts all Heap data and makes it the largest Heap.
Heap-Sort: removes the root node with a bit in the first data and performs a recursive operation for the maximum Heap adjustment.
Before proceeding to the following discussion, we should note that the arrays are all Zero-Based, which means that our heap Data Structure Model will change.

(Zero-Based)
Correspondingly, several calculation formulas should also be adjusted accordingly:
Parent (I) = floor (I-1)/2), I Parent node subscript
Left (I) = 2i + 1, subscript of the Left subnode of I
Right (I) = 2 (I + 1), subscript of the Right subnode of I
MAX-HEAPIFY is used to maintain the nature of the largest heap. It is the core subroutine used to create the largest heap:

(Max-Heapify)
Since the heap still violates the heap nature after one adjustment, recursive tests are required to make the whole heap meet the heap nature. JavaScript can be used to represent the following:

/*** Check from index and keep the maximum heap properties ** @ array ** @ index Check Start subscript ** @ heapSize heap size **/function maxHeapify (array, index, heapSize) {var iMax = index, iLeft = 2 * index + 1, iRight = 2 * (index + 1 ); if (iLeft 

In general, recursion is mainly used in the sub-governance method, but this does not require Sub-governance. In addition, recursive calls require stack pressure/stack clearance, which has a slight performance disadvantage compared with iteration. Of course, according to the 20/80 rule, this can be ignored. But if you think that recursion will make you feel uncomfortable, you can also use iteration, such as the following:

/*** Check from index and keep the maximum heap properties ** @ array ** @ index Check Start subscript ** @ heapSize heap size **/function maxHeapify (array, index, heapSize) {var iMax, iLeft, iRight; while (true) {iMax = index; iLeft = 2 * index + 1; iRight = 2 * (index + 1 ); if (iLeft 

Build-Max-Heap is used to convert an array into a maximum Heap, and two parameters are accepted: array and Heap size, build-Max-Heap calls Max-Heapify from the bottom up to transform the array and create the largest Heap. Because Max-Heapify can ensure that all nodes after the subscripts I meet the nature of the largest heap, the bottom-up call of Max-Heapify can maintain this nature during the transformation process. If the maximum number of Heap elements is n, Build-Max-Heap starts from Parent (n) and calls Max-Heapify sequentially. The process is as follows:

JavaScript is described 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 is an interface algorithm for Heap sorting. Heap-Sort first calls Build-Max-Heap to transform the array into the largest Heap, and then exchanges elements between Heap and Heap, then, the bottom is raised, and Max-Heapify is called again to maintain the maximum heap nature. Since the top element of the heap must be the largest element in the heap, after an operation, the largest element in the heap is separated from the heap. After repeated n-1 times, the array is arranged. The process is as follows:

JavaScript is described 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 implementation
Finally, the complete javascript code is 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. Application of heap Sorting Algorithm

(1) algorithm performance/complexity
The time complexity of heap sorting is very stable (we can see that it is not sensitive to input data). It is O (n ㏒ n) complexity, and the best case is the same as the worst case.
However, the spatial complexity varies depending on the implementation. The preceding two common complexities are discussed: O (n) and O (1 ). Based on the principle of space saving, I recommend the O (1) complexity method.

(2) algorithm Stability
Heap sorting has a large number of filtering and moving processes, which are unstable sorting algorithms.

(3) Application scenarios of Algorithms
Heap sorting generates a large overhead in the process of creating a heap and adjusting the heap. It is not applicable when there are few elements. However, when there are many elements, it is a good choice. Especially when solving problems such as the top n large numbers, 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.