Java data structure and algorithm: Heap __heap

Source: Internet
Author: User
Tags class definition comparable
1. Definition of the heap

The keywords with n data elements are (K0, K1 、...、 kn-1) If they satisfy the following relationship: ki<= k2i+1 and ki<= k2i+2 (or ki>= k2i+1 and ki>= k2i+2) (i=0, 1 、...、 (n-2)/ 2) is called a heap (Heap).

If you store this data element sequence in a one-dimensional array, and the array corresponds to a complete binary tree, the meaning of the heap can be understood to be: in the complete binary tree, any non-terminal node keyword is not greater than (or not less than) its left and right children nodes of the keyword.

The following figure (b), (c) gives examples of the minimum heap and the maximum heap, respectively, the key word for any non terminal node is less than or equal to the key of its left and right child, and the key of the node at the top of the heap (that is, the root node of the complete binary tree) is the smallest of the entire sequence, so call it the smallest heap The key word for any non terminal node is greater than or equal to its left and right child's keyword, at which point the node at the top of the heap is the largest in the entire sequence, so it is called the maximum heap.

The adjustment algorithm Filterdown requires that the subtree with branch node I as the root be adjusted to the minimum heap, the basic idea is: from the node I start downward adjustment, first compare the node I left child node and the right child node of the key word size, if the node I left child node key words less than the right child node keyword, Is adjusted along the left branch of node I, otherwise the right branch of node I is adjusted, and J indicates a child node with a small key value in the algorithm. Then the node I and the node J for the keyword comparison, if the node i keyword is greater than the node J keyword, then the two-node swap position, equivalent to the key word small node floating. The I=j,j=2*j 10 L is then continued to be compared to the next layer, if the keyword of the node i is not greater than the key word of the node J or the node I have no child when the adjustment ends.

Note: the "heap" here refers to a special two-fork tree, and not in programming languages such as Java and C + +.
"Heap" confusion, which refers to the available parts of computer memory that programmers can get with new.

Heap is an introduction to the heap is a complete binary tree is often used to implement each node of the keyword is greater than (equal to) the node's child node keyword

Weak order, priority queue 2. Inserting elements into the heap

The member function insert () in the class definition of the heap is used to insert a data element in the heap, where the data element is always inserted behind the smallest heap that has been built, and the data element with the keyword 14 is inserted in the heap as shown in the following figure. Obviously inserting elements in the heap can destroy the nature of the heap, so you also need to invoke the Filterup () function to make a bottom-up adjustment where the subtree is the heap.

In the class definition of the heap, the member function Deletetop () is used to delete the heap top data element. After the heap top element is removed from the heap, the last element of the heap is generally moved to the top of the heap and the current number of elements of the heap is heapcurrentsize by 1, and the Filterdown () function is eventually called to adjust from the top of the heap. The process of removing the heap top element in the heap is shown in Figure 6-20.

3. Two fork Heap

A binary heap is usually one of the "heaps" in the data structure that we are talking about. As in the past, this paper introduces the theoretical knowledge of the two-fork heap, and then gives the realization of C language. Later, the implementation of C + + and Java version is given; the implementation of the language is different, but the principle is the same, choose one of them to understand the 4. Description of the heap and the two-fork heap definition of the 4.1-heap

Heap (heap), where the heap is called a heap in the data structure, not a heap in the memory model. A heap is usually one that can be seen as a tree, which satisfies the following properties: [Nature] The value of any node in the heap is always no greater than (not less than) the value of its child nodes; [Nature II] The heap is always a complete tree.

A heap that is no more than its child nodes is called a minimum heap or a small Gan, while a heap of any node that is not less than its child nodes is called the maximum heap or heap. The common heap has two fork heap, left-leaning heap, oblique heap, two items heap, Fibonacci Ponachi and so on. definition of 4.2 two fork heaps

The binary heap is a complete two-yuan tree or an approximate complete two-dollar Tree, which is divided into two types: the maximum heap and the smallest heap.
Maximum heap: The key value of the parent node is always greater than or equal to the key value of any one child node; the minimum heap: The key value of the parent node is always less than or equal to the key value of any one child node. The schematic diagram is as follows:

Binary heaps are generally implemented by "arrays". Array implementation of the two-fork heap, the parent node and the location of the child node has a certain relationship. Sometimes we place the first element of the binary heap in the position of the array index 0, sometimes at 1. Of course, they are essentially the same (all two forks), but there are slightly different implementations.
Assuming that the index of the first element in the array is 0, the position of the parent and child nodes is the following: The index of the left child with index i is (2*i+1); The index of the left child index for I is (2*i+2); The index of the parent node of I is floor ((i-1)/2);

Suppose that the index of "first element" in an array is 1, the location relationship between the parent node and the child node is as follows: The index of the left child with index i is (2*i) the index of the left child indexed to I is (2*i+1) the index of the parent node of the index is floor (I/2)

Note: The implementation of the binary heap in this paper is all based on the "binary heap first element in the array index of 0" way. 5. Two-fork heap of graphic analysis

In the front, we have learned that the "Max Heap" and "minimum heap" are symmetric relationships. It also means knowing one of them. The graphics and text parsing in this section is described in the "Max Heap".

The core of the binary heap is "Add node" and "Delete node", understanding these two algorithms, two fork heap also basic master. They are described below. 5.1 Add

Suppose you add 85 to the maximum heap [90,80,70,60,40,30,20,10,50], the steps you need to perform are as follows:

As shown in the figure above, when adding data to the maximum heap: First add the data to the end of the maximum heap, and then move the element up as far as possible until it is moved.

When you add 85 to [90,80,70,60,40,30,20,10,50], the maximum heap becomes [90,85,70,60,80,30,20,10,50,40].

*
 * Maximum heap's upward adjustment algorithm (starting from start up until 0, adjust heap)
 *
 Note: The array implementation of the heap, the nth node of the index value of the left child is (2n+1), the right child's index is (2n+2).
 *
 * Parameter description:
 *     Start-is the starting position of the adjustment point (generally the index of the last element in the array)/
protected void Filterup (int start) {
    int c = start;            Position
    int p = (c-1)/2        for current node The location of the parent node, 
    T-tmp = Mheap.get (c);        The current node size while

    (C > 0) {
        int cmp = Mheap.get (P). COMPARETO (TMP);
        if (CMP >= 0) break
            ;
        else {
            Mheap.set (c, Mheap.get (p));
            c = P;
            p = (p-1)/2;   
        }       
    }
    Mheap.set (c, TMP);
} 
 * * Inserts data into the two-fork heap */public
void Insert (T data) {
    int size = Mheap.size ();

    Mheap.add (data);    Inserts an "array" at the footer
    Filterup (size);        Adjust Heap
} up

The action of Insert (data): Adds the dataset to the maximum heap. Mheap is a dynamic array ArrayList object.

The addition fails when the heap is full, otherwise data is added to the end of the maximum heap. The array is then readjusted to the maximum heap by an upward adjustment algorithm. 5.2 Delete

Suppose you remove 90 from the maximum heap [90,85,70,60,80,30,20,10,50,40], the steps you need to perform are as follows:

As shown in the figure above, when you delete data from the largest heap: Delete the data first, and then insert the space with the last element in the largest heap, and then move the "vacancy" up as far as possible until the remaining data becomes a maximum heap.
After removing 90 from [90,85,70,60,80,30,20,10,50,40], the maximum heap becomes [85,80,70,60,40,30,20,10,50].

Note: Consider removing 60 from the maximum heap [90,85,70,60,80,30,20,10,50,40], the steps performed cannot be simply replaced with its byte points, but must be considered as "the replacement tree is still the largest heap."

* * * Maximum heap's downward adjustment algorithm * Note: The array implementation of the heap, the nth node of the index value of the left child is (2n+1), the right child's index is (2n+2). * * Parameter Description: * Start--The starting position of the reduced node (typically 0, indicating starting from the 1th) * End--up to the range (the index of the last element in the general array)/protected void Filterdown (i          NT start, int end) {int c = start;     The position of the current node int l = 2*c + 1;    The position of the left child (T-tmp = Mheap.get (c));
        The size while (l <= end) of the current node is {int cmp = Mheap.get (L). CompareTo (Mheap.get (l+1));        "L" is the left child, "l+1" is the right child if (L < end && cmp<0) l++;
        Of the left and right two children choose the larger, namely mheap[l+1] cmp = Tmp.compareto (Mheap.get (l));        if (CMP >= 0) break;
            Adjustment end Else {mheap.set (c, Mheap.get (L));
            c = l;   
        L = 2*l + 1;
} mheap.set (c, TMP); * * * Delete Maximum heap data * * return value: * 0, Success *-1, failure/public int remove (T data) {//If heap is empty, return-1 if (Mhea

    P.isempty () = = true) return-1; Gets the index of data in the arrayT index = mheap.indexof (data);

    if (index==-1) return-1;
    int size = Mheap.size ();                Mheap.set (Index, Mheap.get (size-1));//Fill Mheap.remove (size-1) with the last element;    Delete the last element if (Mheap.size () > 1) filterdown (index, Mheap.size ()-1);
Starting from the index position, adjust the minimum heap return 0; }
6. Two-fork heap Java Implementation 6.1 two fork heap (max Heap)
/** * Two-fork heap (max Heap) * * @author Skywang * @date 2014/03/07 * * java.util.ArrayList;

Import java.util.List;    public class Maxheap<t extends comparable<t>> {private list<t> mheap;
    The queue (actually an instance of a dynamic array ArrayList) public maxheap () {this.mheap = new arraylist<t> ();
     * * * Maximum heap's downward adjustment algorithm * Note: The array implementation of the heap, the nth node of the index value of the left child is (2n+1), the right child's index is (2n+2). * * Parameter Description: * Start-the starting position of the reduced node (typically 0, which means starting at the 1th) * End--up to the range (the index of the last element in the general array) * * * protect          ed void Filterdown (int start, int end) {int c = start;     The position of the current node int l = 2*c + 1;    The position of the left child (T-tmp = Mheap.get (c));
            The size while (l <= end) of the current node is {int cmp = Mheap.get (L). CompareTo (Mheap.get (l+1));        "L" is the left child, "l+1" is the right child if (L < end && cmp<0) l++;
    Of the left and right two children choose the larger, namely mheap[l+1] cmp = Tmp.compareto (Mheap.get (l));        if (CMP >= 0) break;
                Adjustment end Else {mheap.set (c, Mheap.get (L));
                c = l;   
            L = 2*l + 1;
    } mheap.set (c, TMP);
        * * * Delete Maximum heap data * * return value: * 0, Success *-1, failure/public int remove (T data) {

        If heap is empty, return-1 if (mheap.isempty () = = true) return-1;
        Gets the index of data in the array int index = MHEAP.INDEXOF (data);

        if (index==-1) return-1;
        int size = Mheap.size ();                Mheap.set (Index, Mheap.get (size-1));//Fill Mheap.remove (size-1) with the last element;    Delete the last element if (Mheap.size () > 1) filterdown (index, Mheap.size ()-1);
    Starting from the index position, adjust the minimum heap return 0;
     * * * Maximum heap's upward adjustment algorithm (starting from start to 0, adjusting heap) * Note: The array implementation of the heap, the nth node of the index value of the left child is (2n+1), the right child's index is (2n+2). * * Parameter Description: * Start--is the starting position of the adjustment point (The index of the last element in a generic array)/protected void Filterup (int start) {int c = start;        position int p = (c-1)/2 for current node        The location of the parent node, T-tmp = Mheap.get (c);
            The current node size while (C > 0) {int cmp = Mheap.get (P). COMPARETO (TMP);
            if (CMP >= 0) break;
                else {Mheap.set (c, Mheap.get (p));
                c = P;   
            p = (p-1)/2;
    } mheap.set (c, TMP);

        * * * Inserts data into the two-fork heap */public void Insert (T data) {int size = Mheap.size ();    Mheap.add (data);        Inserts an "array" at the footer Filterup (size);
        Adjust heap} @Override public String toString () {StringBuilder sb = new StringBuilder ();

        for (int i=0; i<mheap.size (); i++) Sb.append (Mheap.get (i) + "");
    return sb.tostring ();
     public static void Main (string[] args) {   int i;
        int a[] = {10, 40, 30, 60, 90, 70, 20, 50, 80};

        Maxheap<integer> tree=new maxheap<integer> ();
        System.out.printf ("= = add:");
            For (i=0 i<a.length; i++) {System.out.printf ("%d", a[i]);
        Tree.insert (A[i]);

        } System.out.printf ("\n== Max Heap:%s", tree);
        i=85;
        Tree.insert (i);
        System.out.printf ("\n== add element:%d", i);

        System.out.printf ("\n== Max Heap:%s", tree);
        i=90;
        Tree.remove (i);
        System.out.printf ("\n== delete element:%d", i);
        System.out.printf ("\n== Max Heap:%s", tree);
    System.out.printf ("\ n"); }
}
6.2 Two fork heap (minimum heap)
/** * Two-fork heap (Minimum heap) * * @author Skywang * @date 2014/03/07/import java.util.ArrayList;

Import java.util.List;        public class Minheap<t extends comparable<t>> {private list<t> mheap;
    Array of storage heap public minheap () {this.mheap = new arraylist<t> ();
     * * * Note: The index of the left child of the nth node is (2n+1), and the index of the right child is (2n+2) in the heap implemented by the array. * * Parameter Description: * Start-the starting position of the reduced node (typically 0, which means starting at the 1th) * End--up to the range (the index of the last element in the general array) * * * protect          ed void Filterdown (int start, int end) {int c = start;     The position of the current node int l = 2*c + 1;    The position of the left child (T-tmp = Mheap.get (c));
            The size while (l <= end) of the current node is {int cmp = Mheap.get (L). CompareTo (Mheap.get (l+1));        "L" is the left child, "l+1" is the right child if (L < end && cmp>0) l++;
            Of the left and right two children select the lesser, i.e. mheap[l+1] cmp = Tmp.compareto (Mheap.get (l)); if (cmP <= 0) break;
                Adjustment end Else {mheap.set (c, Mheap.get (L));
                c = l;   
            L = 2*l + 1;
    } mheap.set (c, TMP); * * * Minimum heap Delete * * return value: * Successful, return the deleted value * failed, return null/public int remove (T data

        {//If heap is empty, return-1 if (mheap.isempty () = = true) return-1;
        Gets the index of data in the array int index = MHEAP.INDEXOF (data);

        if (index==-1) return-1;
        int size = Mheap.size ();                Mheap.set (Index, Mheap.get (size-1));//Fill Mheap.remove (size-1) with the last element;    Delete the last element if (Mheap.size () > 1) filterdown (index, Mheap.size ()-1);
    Starting from the index position, adjust the minimum heap return 0;
     * * * * minimum heap upward adjustment algorithm (starting from start to 0, adjusting heap) * Note: The array implementation of the heap, the nth node of the index value of the left child is (2n+1), the right child's index is (2n+2). * * Parameter Description: * Start--is the starting position of the adjustment point (generally the last one in the array)Index of Element) */protected void Filterup (int start) {int c = start;        position int p = (c-1)/2 for current node        The location of the parent node, T-tmp = Mheap.get (c);
            The current node size while (C > 0) {int cmp = Mheap.get (P). COMPARETO (TMP);
            if (CMP <= 0) break;
                else {Mheap.set (c, Mheap.get (p));
                c = P;   
            p = (p-1)/2;
    } mheap.set (c, TMP);

        * * * Inserts data into the two-fork heap */public void Insert (T data) {int size = Mheap.size ();    Mheap.add (data);        Inserts an "array" at the footer Filterup (size);
        The heap} public String toString () {StringBuilder sb = new StringBuilder () is adjusted up.

        for (int i=0; i<mheap.size (); i++) Sb.append (Mheap.get (i) + "");
    return sb.tostring ();
        public static void Main (string[] args) {int i; int a[] = {80, 40, 30, 60, 90, 70, 10, 50, 20};

        Minheap<integer> tree=new minheap<integer> ();
        System.out.printf ("= = add:");
            For (i=0 i<a.length; i++) {System.out.printf ("%d", a[i]);
        Tree.insert (A[i]);

        } System.out.printf ("\n== Minimum heap:%s", tree);
        i=15;
        Tree.insert (i);
        System.out.printf ("\n== add element:%d", i);

        System.out.printf ("\n== Minimum heap:%s", tree);
        i=10;
        Tree.remove (i);
        System.out.printf ("\n== delete element:%d", i);
        System.out.printf ("\n== Minimum heap:%s", tree);
    System.out.printf ("\ n"); }
}
6.3 Two-fork heap Java test program

The test program is already included in the corresponding implementation file, which shows only the results of the operation.

Maximum Heap (Maxheap.java) Run Result:

= = Add: The largest heap: = = = = = = = = = = = = = = = = = = = = 
max. 
add:
90 85 70 60 80 
Delete elements: 90

Run result of minimum heap (Minheap.java):

= = Minimum heap: =% = = = 
add element: =
= Min. minimum heap: 10 = = 
Delete element

The PS. Two fork Heap is the theoretical cornerstone of "heap sequencing". Later on the algorithm will be explained to "heap sorting", Understanding the "binary heap", "heap sorting" is very simple

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.