Simple implementation of heap ordering

Source: Internet
Author: User

Heap sorting is a sort of, generally have big root pair and small Gan said, propped pair, the root node value is larger than the value of the root node of the left and right Sub-tree. Build a heap we are generally a completely binary tree. Heap ordering is generally oriented to a large amount of data, when the amount of data is small, not suitable for the use of heap sorting, for example, There is a situation is the implementation of the TOPN algorithm, generally with the help of a large root pair to achieve, scanning massive data, The huge amount of data in the largest of the top N data into the HEAP. When implemented below, for the sake of simplicity, the array used to store the binary tree, which is a sequential tree, is not only a review of the contents of the heap ordering, but also a review of some related operations of the two fork Tree.

Some properties of the complete binary tree, the root node root is 1, the total number of nodes is n, then the first non-leaf node is the [n/2] Node. In the order book, the left child of node I should be 2*i and the right child is 2*i+1.

Heap sorting, The first thing to do is to first build an initial heap, assuming that the data to be sorted is 10, then the binary tree is stored in a arr[10] array

(1) the initial heap, here is the big root heap. Start with the position of [n/2] in accordance with the principle of propped and adjust to the root Node. So I got the initial big root heap.

(2) the root node at the top of the Dagen must be the largest element. Next we sort by n-1 Times. i = 0; I < n-1, each time the root and arr[n-i+1] is exchanged, then the arr[n-i+1] from the top of the book, and then from the top down to Adjust. Look directly at the Code.

1 /**2 * According to large (small) Gan rules, from top to down to adjust the heap recursive implementation3      * @parami the array index of the current subtree node in the order tree4      * @paramThe heap represents a two-tree of the heap, which is actually an array of sequential5      * @paramEnd flag The index position of the last node of this binary tree6      */7      public Static voidUptodown (intIint[] heap,intEnd) {8         intleft = i*2+1;//index of the left child9         intright = left + 1;//Index of Right childTen          one         if(right <= End)//the kids are not empty . a         { -             intpos = heap[left]>heap[right]?left:right; -             if(heap[pos] >heap[i]) the             { -                 intTMP =heap[i]; -heap[i] =heap[pos]; -heap[pos] =tmp; +             } - uptodown (left, heap, end); + uptodown (right, heap, end); a}Else{ at             if(left >End) -                 return; -             Else{ -                 if(heap[left] >heap[i]) -                 { -                     intTMP =heap[i]; inheap[i] =heap[left]; -heap[left] =tmp; to                 } + uptodown (left, heap, end); -             } the         } *}

next, Create the initial heap:

1 /**2 * Wear the initial heap of pieces3      * @paramstorage array corresponding to the heap heap4      */5      public Static voidCreateheap (int[] Heap) {6          for(inti = heap.length/2-1; I >=0; i--)7Uptodown (i, heap, heap.length-1);8}

To sort the heap:

1 /*2 * Use an array of simple simulated heap sorting3      */4      public Static voidHeapsort (int[] Heap) {5         6          for(inti = 0; I < heap.length-1; i++)7         {8             intTMP = Heap[0];9             intEnd = Heap.length-i-1;Tenheap[0] =heap[end]; oneheap[end] =tmp; aUptodown (0, heap, end-1); -         } the}

After the above sort, the elements in the pair are ordered, and then the array can be omitted in Order.

The following operations are tree-related operations, mainly including the number of nodes to find the book, the height of the tree, recursive traversal of the tree and Non-recursive traversal. finally, draw a diagram as an example.

(1) the number of tree leaf nodes, ideas: left dial hand tree nodes + right subtree node number +1.

1 /**2 * Recursion to find the height of the tree3      * @paraman array of heap storage trees4      * @paramroot root node5      * @returnreturns the height of the Tree. 6      */7      public Static intGetNode (int[] heap,intRoot)8{//Recursive tree nodes (number of left subtree nodes + right subtree nodes + root node number)9         intleft = root*2+1;Ten         intright = left +1; one         intEnd = heap.length-1;//the index of the last element of the current tree a          -         if(root >End) -             return0; the         if(left>end && Right >End) -             return1; -         returnGetNode (heap, left) + getnode (heap, Right) + 1; -}

(2) the height of the tree, the Idea: Max (height of the left subtree, height of the right sub-tree) +1

1  public Static intGetHeight (int[] heap,intRoot)2{//Saozi The taller one in the right subtree, plus 1.3         intleft = root*2+1;4         intright = left +1;5         intEnd = Heap.length-1;6         7         8         if(root > End)return0;9         Ten         if(left>end && Right >End) one             return1; a          -         returnMath.max (getheight (heap, left), getheight (heap, right)) + 1; -}

(3) the recursive traversal of the tree, the first root sequence, the root sequence, the latter is very similar to the root sequence, here just write the first root sequence recursive traversal code

1  public Static voidPretransverse (int[] heap,intI) {2         intleft = i*2+1;3         intright = left +1;4         5         if(i > Heap.length-1)6             return;7System.out.print (heap[i]+ ",");8 pretransverse (heap, left);9 pretransverse (heap, right);Ten}

The placement of Pretransverse (heap, left) and Pretransverse (heap, Right) primarily determines the traversal order after the First.

non-recursive, traversing a binary tree, which will use the stack data structure. of course, non-recursive traversal, can also be divided into the first order, the sequence and order, the same idea, here this record with the help of the stack of non-recursive First order traversal binary Tree. Tree structure is actually a special case of the graph, and the binary tree is undoubtedly a more special figure, the binary tree of the first order traversal is actually equivalent to the depth of the map of the first DFS Traversal. The idea of a non-recursive two-tree line-sequence traversal is simple:

(1) The current node root is empty, not empty words to access, and the node into the stack, and get the current Node's left child p = p*2+1, Sequential storage binary tree, binary tree root node index is 0

(2) if the currently accessed node is an empty node, then pop the top element p = stack[--cn] and get its right child, p = p*2+2.

(3) repeat cycle (1) (2) know access to play all nodes, or stack is empty

1 /**2 * Non-recursive now need to facilitate a binary tree using the stack3      * @paramHeap4      */5      public Static voidPreprint (int[] Heap)6     {7         intHeight = getheight (heap, 0);8         int[] stack =New int[height];9         intp = 0;Ten         intCN = 0; one         intEnd = Heap.length-1; a          -          while(p<=end | | cn!=0){ -             if(p <=End) the             { -System.out.print (heap[p]+ ","); -stack[cn++] = p;//LfT child -p = p*2+1; +             } -             Else{ +p = stack[--cn]; ap = p*2+2;// right Child at             } -         } -}

With queues, the binary tree is traversed hierarchically. Thought is also simple:

(1) first to queue the root node

(2) when the queue is out of the team, it accesses the child node of the element that is Visited.

(3) repeat the above two operations, knowing that the queue is empty when the End.

1 //Non-recursive Layering facilitates the use of queues2      public Static voidBroadtranverse (int[] Heap)3     {4Linkedlist<integer> que =NewLinkedlist<integer>();5         intEnd = Heap.length-1;6         7Que.offer (0);8          while(que.isempty () = =false)9         {Ten             intp =Que.poll (); oneSystem.out.print (heap[p]+ ","); a             intleft = p*2+1; -             intright = left +1; -             if(left <=End) Que.offer (left); the             if(right <=End) Que.offer (right); -         } -}

Simple implementation of heap ordering

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.