Java Implementation of heap (3)

Source: Internet
Author: User

In summary, two heaps are implemented through C and C ++ respectively. This chapter provides the Java version of the two heaps. As the old saying goes, the three implementations share the same principle. You just need to know one of them. Directory 1. introduction to the two-item tree 2. introduction to item 2 heap 3. 2. Basic operations on heap 4. java Implementation of the two items heap (complete source code) 5. two heap Java test program reproduced please indicate the source: http://www.cnblogs.com/skywang12345/p/3656098.html more content: Data Structure and algorithm series directory (01) Two heap (1) graph Analysis and C language implementation (02) Item 2 heap (2) item C ++ implementation (03) Item 2 heap (2) java implementation two-item Tree Introduction two-item tree definition two-item heap is a set of two-item trees. Before learning about the second heap, we will introduce the second tree. The binary tree is a recursive ordered tree. Its Recursive definition is as follows: (01) the binary tree B0 has only one node; (02) the binary tree Bk is composed of two binary trees B (k-1, one tree is the leftmost child of the other tree root. As shown in: B0, B1, B2, B3, and B4 are two trees. Compared with the definition of the two-term tree mentioned above: B0 has only one node, B1 is composed of two B0 S, B2 is composed of two B1 S, and B3 is composed of two B2 S, b4 is composed of two B3 trees. When two identical two trees form another tree, one of them is the leftmost child of the other tree. The properties of the two trees: [Nature 1] Bk has 2 K nodes. As shown in, B0 has 20 = 1 nodes, B1 has 21 = 2 nodes, B2 has 22 = 4 nodes, and... [nature 2] Bk's height is k. As shown in, the B0 height is 0, the B1 height is 1, and the B2 height is 2 ,... [nature 3] Bk has exactly C (k, I) nodes in depth I, where I =, 2 ,..., k. C (k, I) is a factorial element in high school mathematics. For example, C (10, 3) = (10*9*8)/(3*2*1) = node C (4, 0) with a depth of 0 in 240 B4 = node C (4, 1) with a depth of 1 in 1 B4) = 4/1 = node C () with a depth of 2 in 4 B4 = (4*3)/(2*1) = node C () with a depth of 3 in 6 B4) = (4*3*2)/(3*2*1) = node C (4, 4) with a depth of 4 in 4 B4 = (4*3*2*1) /(4*3*2*1) = 1. The Node Distribution of B4 is (, 1 ). [Nature 4] The root degree is k, which is greater than the degree of any other node. The node level is the number of Subtrees owned by the node. Note: The height and depth of the tree are the same. For the concept of tree height, the height of a tree with only one node in introduction to algorithms is 0, while that of a tree with only one node in Wikipedia is 1. This article uses the concept of "tree height and depth" in "Introduction to algorithms. The introduction of the two-way heap is the same as that of the previous heap (two-way heap, left-leaning heap, and oblique heap). It is also used to implement the priority queue. A two-way heap is a set of two-way trees that meet the following requirements: (01) each two-way tree meets the minimum heap nature. That is, the keyword of the parent node <= the keyword of its child. (02) two or more trees cannot have the same degree (including 0 ). In other words, two trees with k degrees have 0 or 1. Is a two-item heap, which consists of two trees B0, B2, and B3. Comparison of Two-item heap definitions: (01) Two-item tree B0, B2, and B3 are the minimum heap; (02) Two-item heap does not contain two trees of the same degree. The second heap (01) ensures that the minimum node of the second heap is the root node of a second tree. The second heap (02) if the number of nodes is n, only log {n} + 1 second tree is supported. In fact, if a two-item heap Containing n nodes is expressed as an index of several two (or converted to binary), each two indexes correspond to a two-item tree. For example, the sum of the two indices of 13 (binary is 1101) is 13 = 23 + 22 + 20. Therefore, the number of two heap items with 13 nodes ranges from 3 to 2, 0 is composed of three two trees. The basic operation of the two-way heap can be merged, and the complexity of its merge operation is O (log n ). 1. basic definition copy code public class BinomialHeap <T extends Comparable <T >>{ private BinomialNode <T> mRoot; // root node private class BinomialNode <T extends Comparable <T> {T key; // key (key value) int degree; // level BinomialNode <T> child; // BinomialNode of the left child <T> parent; // BinomialNode of the parent node <T> next; // public BinomialNode (T key) {this. key = key; this. degree = 0; this. child = null; this. parent = null; this. next = nul L;} public String toString () {return "key:" + key ;}}...... copy the code BinomialNode as the node of the two items heap. It includes the keyword (key), used to compare the node size; degree (degree), used to indicate the degree of the current node; left child (child), parent node (parent) and the sibling node (next ). BinomialHeap is a class corresponding to the two-item heap. It includes the root node mRoot of the two items heap and the basic operation definition of the two items heap. Below is the relationship between the tree structure of a Two-item heap and its memory structure. 2. The merge operation is the focus of the two items heap, and its addition operation is also implemented based on the merge operation. The steps required to merge two heap items are summarized as follows: (01) combine the root linked list of the two heap items into a linked list. The merged new linked list is arranged monotonically in ascending order according to "node level. (02) connect "two tree with the same root node degree" in the new linked list until all root nodes have different degrees. Next, let's take a look at the merging operation code, and then describe the merging operation. Merge () Code (Java) View Codelink () Code (Java) View Code merge operation Code (Java) Copy Code 1/* 2 * merge two items heap: merge h1, h2 is merged into a heap, And the merged heap 3 */4 private BinomialNode <T> union (BinomialNode <T> h1, BinomialNode <T> h2) is returned) {5 BinomialNode <T> root; 6 7 // combine the root tables in h1 and h2 into a list of root 8 root = merge (h1, h2) in ascending order of degrees ); 9 if (root = null) 10 return null; 11 12 BinomialNode <T> prev_x = null; 13 BinomialNode <T> x = root; 14 BinomialNode <T> next_x = x. next; 15 while (next_x! = Null) {16 17 if (x. degree! = Next_x.degree) 18 | (next_x.next! = Null) & (next_x.degree = next_x.next.degree) {19 // Case 1: x. degree! = Next_x.degree20 // Case 2: x. degree = next_x.degree = next_x.next.degree21 prev_x = x; 22 x = next_x; 23} else if (x. key. compareTo (next_x.key) <= 0) {24 // Case 3: x. degree = next_x.degree! = Next_x.next.degree25 // & x. key <= next_x.key26 x. next = next_x.next; 27 link (next_x, x); 28} else {29 // Case 4: x. degree = next_x.degree! = Next_x.next.degree30 // & x. key> next_x.key31 if (prev_x = null) {32 root = next_x; 33} else {34 prev_x.next = next_x; 35} 36 link (x, next_x); 37 x = next_x; 38} 39 next_x = x. next; 40} 41 42 return root; 43} 44 45/* 46 * merge two heap others into the current heap 47 */48 public void union (BinomialHeap <T> other) {49 if (other! = Null & other. mRoot! = Null) 50 mRoot = union (mRoot, other. mRoot); 51} The combine (h1, h2) function of the copy code merging function combines h1 and h2 and returns the merged two-item heap. In combine (h1, h2), two functions are involved: merge (h1, h2) and link (child, root ). Merge (h1, h2) is what we mentioned above. "The root linked list of two items heap is merged into a linked list. The new linked list after the merger is sorted in a monotonically ascending order by 'degree of node ". Link (child, root) is an auxiliary function for merging operations, it sets "root node of two heap child" to "left child of two heap root" to integrate child into root. When merging h1 and h2 in combine (h1, h2), first use merge (h1, h2) combine the root linked lists of h1 and h2 into a "monotonically increasing by node degree" linked list. Then, enter the while loop to traverse the merged new linked list, connect the "two tree with the same root node degree" in the new linked list until all root nodes have different degrees. When we connect the two tree with the same root node degree in the new join table, we can summarize the connection conditions into four types. X is the current node of the root linked list, And next_x is the next (brother) node of x. Case 1: x-> degree! = Next_x-> degree: when the "degree of the current node" is equal to the "degree of the next node. In this case, you do not need to perform any operations. continue to view the subsequent nodes. Case 2: x-> degree = next_x-> next-> degree, when the "Degree of the current node", "level of the next node", and "level of the next node" are equal. At this time, do not perform any operation for the moment, or continue to view the following nodes. In fact, this is to wait until the "next node" and "next node" are integrated. Case 3: x-> degree = next_x-> degree! = Next_x-> next-> degree & x-> key <= next_x-> key, that is, "the degree of the current node" is equal to "the degree of the next node, and "key value of the current node" <= "level of the next node ". In this case, the "next node (corresponding to the two-item tree)" is used as the "Left child of the current node (corresponding to the two-item tree ". Case 4: x-> degree = next_x-> degree! = Next_x-> next-> degree & x-> key> next_x-> key, that is, "the degree of the current node" is equal to "the degree of the next node, and "key value of the current node"> "level of the next node ". In this case, the "current node (corresponding to the two-item tree)" is used as the "Left child of the next node (corresponding to the two-item tree ". The following describes the merge operations. Step 2: merge the two-item heap root linked lists into one linked list. After step 2 is completed, the new linked list contains many two trees with the same degree. In fact, what we get is corresponding to "Case 4". "tree 41" (the second tree with the root node 41) has the same degree as "tree 13, and the key value of "tree 41"> "tree 13. In this case, "tree 41" is used as the left child of "tree 13. Step 1: merge "tree 41" and "tree 13". After step 3 is completed, the result corresponds to "Case 3, "tree 13" has the same degree as "tree 28", and "tree 13" has the key value <"tree 28. In this case, "tree 28" is used as the left child of "tree 13. Step 2: merge "tree 13" and "tree 28". After step 2 is completed, the result corresponds to "Case 2, tree 13, tree 28, and tree 7 have the same degrees. Set x to the next node. Step 2: Move x and next_x back and execute Step 2. The result is the same as "Case 3". The degrees of "tree 7" and "tree 11" are the same, and the key value of "tree 7" <"tree 11. In this case, "tree 11" is used as the left child of "tree 7. Step 2: merge "tree 7" and "tree 11". After step 2 is completed, the result corresponds to "Case 4, "tree 7" and "tree 6" have the same degree, and "tree 7" has a key value> "tree 6. In this case, "tree 7" is used as the left child of "tree 6. Step 2: merge "tree 7" and "tree 6". The merge operation is complete! PS. The graphic parsing process of the merge operation corresponds to the testUnion () function in the test program (Main. java! 3. After the insert operation understands the "merge" operation, the insert operation is quite simple. The insert operation can be considered to merge the "Node to be inserted" with the existing heap. Insert operation code (Java) Copy code 1/* 2 * to create a node corresponding to the key, and insert it into the two heap. 3 */4 public void insert (T key) {5 BinomialNode <T> node; 6 7 // disable insertion of the same key value 8 if (contains (key) = true) {9 System. out. printf ("insert failed: the key (% s) is existed already! \ N ", key); 10 return; 11} 12 13 node = new BinomialNode <T> (key); 14 if (node = null) 15 return; 16 17 mRoot = union (mRoot, node); 18} When copying code, first use contains (key) to find the node with the key value. If a node exists, it is returned directly. If the node does not exist, the BinomialNode object is created, and the node and heap are merged. Note: The second heap I implemented here is "insert the same node in hexadecimal format "! If you want to allow insertion of nodes with the same key value, block the contains (key) code in the insert operation. 4. the steps required to delete a node in the two items heap are summarized as follows: (01) Switch "the node" to the root node location of "the two items tree. The method is to traverse from "this node" continuously up (that is, to the root of the tree) "and constantly exchange data between the parent node and the child node until the deleted key value reaches the root of the tree. (02) Remove "the second tree of the node" from the second heap, and record the two heap as heap. (03) Reverse the "Two Tree of the node. The reversal means to separate all the children at the root, integrate these children into two heaps, and mark the two as child. (04) Merge child and heap. Next, let's take a look at the delete operation code. Delete operation code (Java) Copy code 1/* 2 * delete a node: delete a node with a key value 3 */4 private BinomialNode <T> remove (BinomialNode <T> root, T key) {5 if (root = null) 6 return root; 7 8 BinomialNode <T> node; 9 10 // search for the key-value node 11 if (node = search (root, key) = null) 12 return root; 13 14 // move the data of the deleted node to the root node of its two-item tree. 15 BinomialNode <T> parent = node. parent; 16 while (parent! = Null) {17 // exchange data 18 T tmp = node. key; 19 node. key = parent. key; 20 parent. key = tmp; 21 22 // the next parent node 23 node = parent; 24 parent = node. parent; 25} 26 27 // locate the previous root node of the node (prev) 28 BinomialNode <T> prev = null; 29 BinomialNode <T> pos = root; 30 while (pos! = Node) {31 prev = pos; 32 pos = pos. next; 33} 34 // remove node 35 if (prev! = Null) 36 prev. next = node. next; 37 else38 root = node. next; 39 40 root = union (root, reverse (node. child); 41 42 // help GC43 node = null; 44 45 return root; 46} 47 48 public void remove (T key) {49 mRoot = remove (mRoot, key); 50} copy the code remove (key) to delete the node with the key value in the two heap keys and return the two heap items after the node is deleted. The following describes the delete operation (delete node 20 in the two heap ). The general idea is to isolate the deleted node from its two-item tree, and then process the two-item tree accordingly. PS. The graphic parsing process of the delete operation corresponds to the testDelete () function in the test program (Main. java! 5. The update operation updates a node in the heap, which is to modify the value of the node. It consists of two parts: "reducing the value of the node" and "adding the value of the node ". Update the operation code (Java) copy the code/** update the key value of the node in the heap as key */private void updateKey (BinomialNode <T> node, T key) {if (node = null) return; int cmp = key. compareTo (node. key); if (cmp <0) // key <node. key decreaseKey (node, key); else if (cmp> 0) // key> node. key increaseKey (node, key); else System. out. println ("No need to update !!! ");}/** Update the oldkey of the two heap key to newkey */public void update (T oldkey, T newkey) {BinomialNode <T> node; node = search (mRoot, oldkey); if (node! = Null) updateKey (node, newkey);} It is easy to copy code 5.1 to reduce the value of a node and reduce the value of a node: the node must be in a two-item tree, to reduce the value of a node in the "two-item Tree", make sure that "the two-item tree is still a minimum Heap". Therefore, we need to constantly raise the node. Reduce operation code (Java) Copy code 1/* 2 * reduce the keyword value: reduce the node key value in the two items heap to the key. 3 */4 private void decreaseKey (BinomialNode <T> node, T key) {5 if (key. compareTo (node. key)> = 0 | contains (key) = true) {6 System. out. println ("decrease failed: the new key (" + key + ") is existed already, or is no smaller than current key (" + node. key + ")"); 7 return; 8} 9 node. key = key; 10 11 BinomialNode <T> child, parent; 12 child = node; 13 parent = node. parent; 14 while (parent! = Null & child. key. compareTo (parent. key) <0) {15 // exchange the data of parent and child 16 T tmp = parent. key; 17 parent. key = child. key; 18 child. key = tmp; 19 20 child = parent; 21 parent = child. parent; 22} 23} copy the code below: reduce the operation (20-> 2) reduce the operation idea is very simple, is to "keep the minimum heap nature of the Two-item tree where the nodes are subtracted ". PS. The graphic parsing process for reducing operations corresponds to the testDecrease () function in the test program (Main. java! 5.2 adding a node value is also easy. As mentioned above, the number of nodes to be reduced is constantly increased to ensure the minimum heap nature of the "two-item tree where the nodes to be reduced are located; the addition operation continuously reduces the number of added nodes to ensure the minimum heap nature of the "two-way tree of the added nodes. Add operation code (Java) to copy code 1/* 2 * to add the keyword value: Increase the node key value in the two items heap to the key. 3 */4 private void increaseKey (BinomialNode <T> node, T key) {5 if (key. compareTo (node. key) <= 0 | contains (key) = true) {6 System. out. println ("increase failed: the new key (" + key + ") is existed already, or is no greater than current key (" + node. key + ")"); 7 return; 8} 9 node. key = key; 10 11 BinomialNode <T> cur = node; 12 BinomialNode <T> child = cur. child; 13 while (child! = Null) {14 15 if (cur. key. compareTo (child. key)> 0) {16 // If "current node" <"its left child ", 17 // find the smallest node in "its children (left child and left child's brother; 18 // then swap the "minimum node value" and "current node value" 19 BinomialNode <T> least = child; // least is the minimum node 20 while (child. next! = Null) {21 if (least. key. compareTo (child. next. key)> 0) 22 least = child. next; 23 child = child. next; 24} 25 // The Minimum switching node and the current node value 26 T tmp = least. key; 27 least. key = cur. key; 28 cur. key = tmp; 29 30 // after data is exchanged, adjust the "original minimal node" to satisfy the properties of the minimum heap: parent node <= child node 31 cur = least; 32 child = cur. child; 33} else {34 child = child. next; 35} 36} 37} copy the code. below is the idea of adding an operation (6-> 60, "maintain the minimum heap property of the two tree where the added vertex is located ". PS. The graphic parsing process for adding operations corresponds to the testIncrease () function in the test program (Main. java!

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.