Heap ordering of data structure basics (Java implementation) __arcinfo

Source: Internet
Author: User
Summary

This article addresses http://blog.csdn.net/never_cxb/article/details/50211631

Recently to do a pen test questions Baidu has 20 arrays, each has 500 elements, ascending arrangement, find the first 500 of the number, review the heap sorting, summed up, with the implementation of the source code.

Heap Ordering (heapsort) is a sort algorithm designed by using the data structure of a stacked tree (heap), which is a sort of selection. Heap

See the book and other blogs say heap sorting is in place, so the complexity of the space is O (1). A bit of doubt, like I have an array, build a minimum heap, and then fetch the vertices of the smallest heap at a time. Building the smallest heap requires extra space.
Without further scrutiny, the merge sort requires extra space compared to the heap sort.

The heap is a complete binary tree, so it can be represented by an array. The common two-fork tree needs to be represented by a linked list.

A complete binary tree is not equal to a two-forked tree. The following figure is a complete binary tree.

We array subscript starting from 0.

We can get the coordinate formula before the parent node and the child node.

Leftchild = 2*parent+1;
Rightchild = 2*parent +2;
Parent = (child-1)/2;//child for Leftchild  
Insert Heap

From the picture captured in the book, note that the book describes the largest heap, our code is to achieve the smallest heap.

After the heap is inserted, the nature of the parent node > child node is saved.

How to implement the code algorithm. We need to keep the properties of the maximum heap, and after inserting the elements, we must move the array.
The following approach is to first insert the element to the end of the array, and then compare the element and the father element to determine if the swap is needed. Repeat the steps above to know that the traversal is complete or that the heap is already the largest heap.


Code

    /**
     * Add a new element, the step is 1. First insert the element to the end of the list 2. Compare the end element to its parent element, if less than, swap both 3.
     * Repeat the above steps until the vertex position or the child element is greater than the parent element 4. It is not necessary to traverse all the elements of the heap, and to reach the nature of the heap will end prematurely
     * @param array */public
    void Add (E array) {

        data.add (array);

        int child = Data.size ()-1;
        int parent = (child-1)/2;

        Determines whether to reach the vertex
        while (Child > 0) {
            //parent element is greater than subelements, Exchange, keep the parent is small
            if (data.get (parent). CompareTo (Array) > 0) { C14/>data.set (Child, Data.get (parent));
                Data.set (parent, array);

                Child = parent;
                Parent = (child-1)/2;
            } else {
                //is already the smallest heap, no longer need to compare break
                ;
            }
    }

It uses the insertion method to make full use of the properties of the original maximum heap. It's a great idea. To Delete a vertex element

Delete elements, I do not think of a good way. Reading on the only understand, but also the use of exchange ideas.
Deletes the vertex element and then moves the last element to the vertex. And then from the top down, to determine whether the vertex element and its child nodes meet the nature of the heap, is not satisfied with the exchange. Repeat the steps above to know that the traversal is complete or that the heap is already the largest heap.

Note Delete and insert elements, do not necessarily need to traverse the binary tree all layers, when the maximum heap has been satisfied with the nature of the time can be completed.


Code

    /** * Delete the element at the vertex, the step is: 1. Copy the end element to the vertex at 2.
     Then the value of the vertex and the left and right subtree are compared, and the property of the minimum heap is 3. * Swap vertices and left and right subtrees with a smaller value of 4. Repeat the above steps until you have completed the minimum heap or traverse 5.
     Note that there may be a left subtree present, and the right subtree does not exist in 6. 
            * Not necessarily traversing all the elements of the heap, reaching the nature of the heap will end prematurely * @return return the deleted element */public E removetop () {if (Data.isempty ())

        return null;

        E removed = data.get (0);
        Because the last element is exchanged, it is saved here E-Data.get (Data.size ()-1);
        Data.set (0, last);

        Data.remove (Data.size ()-1);
        int parent = 0;
        int leftchild = parent * 2 + 1;

        int rightchild = parent * 2 + 2;
            while (Leftchild <= data.size ()-1) {int minindex = Leftchild; The right subtree is present, judging which is small, the left subtree, save the coordinates//if not present, then use the coordinates///save the coordinates of the smaller elements, you can omit to consider the existence of the left and right subtrees, and only the case if (RI
                    Ghtchild <= data.size ()-1) {if (Data.get (rightchild). CompareTo (Data.get (leftchild)) < 0) {
                Minindex = Rightchild;

}
            }            if (Data.get (Minindex). CompareTo (last) < 0) {Data.set (parent, Data.get (Minindex));
                Data.set (Minindex, last);
                parent = Minindex;
                Leftchild = parent * 2 + 1;
            Rightchild = parent * 2 + 2;
    else {break;//The nature of the minimum heap has been reached} return removed; }

Note: The code needs to consider the presence of the left and right subtrees, only the Zoozi tree. (only the right subtree exists is not possible). So the parent needs to swap with left or right.
I would have used a whole bunch of if judgments.

Reading on the very concise, first set minindex = Leftchild; (Because Zuozi is definitely present), then compare the Saozi right subtree if the right subtree exists. If the right child tree is small, minindex = Rightchild; Otherwise the minindex will not change. Then you can compare minindex and parent.

My previous approach was to compare the left and right subtrees first. Find the smaller tree and compare it with parent. Then consider the case of the left subtree, comparing the left subtree and parent. This method is very redundant. to sort by using a heap

First the original data into the heap, and then the vertex elements are taken out sequentially. Note that if the maximum heap is available, the descending order is obtained. If it's the smallest heap, it gets ascending. Complexity of Time

The heap is a two-fork tree implementation, for n elements, to build two-fork tree, the number of depth is log (n).
The Add method tracks the path of the vertex to the bottom leaf node, the length of which is the depth of the tree, log (n).
For creating a binary tree, adding an element requires up to log (n) steps. So the element addition requires Nlog (n) steps.
Note that if the original data is ascending, the best scenario for building a minimum heap is the worst scenario for building a maximum heap time.

To sort, you also need to call the N-time Remove method, each Remove method requires a log (n) step. Nlog (n) of the total time required. All Code

/** * Minimum heap and heap ordering, minimum heap, vertex element is the minimum value, according to the "Java language programming Step" p83 rewrite, the book is the largest heap. Heap Sort * Save the elements in the smallest heap, remove the vertex elements from the smallest heap each time * * @author tomchen * * * * @param <E>/public class Minheap<e extends Compa rable> {//test program public static void Main (string[] args) {Random r = new Random (System.currenttimemill

        Is ()); 

            Test 10 for (int t = 0; t < t++) {minheap<integer> heap = new minheap<integer> ();

            int msize = R.nextint (15);



            integer[] Original = new Integer[msize];
            The length and elements of the heap are random for (int i = 0; i < msize i++) {Original[i] = r.nextint (100);
            //copy array, the method that invokes the standard library integer[] copy = arrays.copyof (original, msize);

            Arrays.sort (copy);

            Here the output original or disorderly, proof that the order of copy does not affect System.out.println ("Original data:" + arrays.tostring (original)); System.out.println ("Other sorted data:" + ARRAys.tostring (copy));

            Call Heap Sort Heapsort (original);


            SYSTEM.OUT.PRINTLN ("Sorted data:" + arrays.tostring (original));

            System.out.println ("Two sort Eqyal:" + arrays.equals (copy,original));
        System.out.println ("-----------------------------------------"); } public static <e extends comparable> void Heapsort (e[] array) {minheap<e> heap = new Mi
        Nheap<e> ();
        for (int i = 0; i < Array.Length i++) {heap.add (array[i]);

        } System.out.println ("Debug:heap is" + heap);
        for (int i = 0; i < Array.Length i++) {Array[i] = Heap.removetop ();

    } private arraylist<e> data = new arraylist<e> (); Public minheap () {}/** * Adds a new element, the step is 1. First insert the element at the end of the list 2.
     Compares the end element with its parent element, if less than, swapping both 3. * Repeat the above steps until the vertex position or the child element is greater than the parent element 4. It is not necessary to traverse all the elements of the heap, to reach the nature of the heap and to end prematurely * @param array
     */public void Add (E array) {Data.add (array);
        int child = Data.size ()-1;

        int parent = (child-1)/2; Determines whether to reach the vertex while (Child > 0) {//parent element is greater than subelements, Exchange, keep the parent is small if (data.get (parent). CompareTo (AR
                Ray) > 0) {data.set (Child, Data.get (parent));

                Data.set (parent, array);
                Child = parent;
            Parent = (child-1)/2;
            else {//is already the smallest heap, no longer need to compare break; /** * Deletes the element at the vertex, the procedure is: 1. Copy the end element to the vertex at 2.
     Then the value of the vertex and the left and right subtree are compared, and the property of the minimum heap is 3. * Swap vertices and left and right subtrees with a smaller value of 4. Repeat the above steps until you have completed the minimum heap or traverse 5.
     Note that there may be a left subtree present, and the right subtree does not exist in 6. 
            * Not necessarily traversing all the elements of the heap, reaching the nature of the heap will end prematurely * @return return the deleted element */public E removetop () {if (Data.isempty ())

        return null;

        E removed = data.get (0);
        Because the last element is exchanged, it is saved here E-Data.get (Data.size ()-1); Data.set (0, last);

        Data.remove (Data.size ()-1);
        int parent = 0;
        int leftchild = parent * 2 + 1;

        int rightchild = parent * 2 + 2;
            while (Leftchild <= data.size ()-1) {int minindex = Leftchild; The right subtree is present, judging which is small, the left subtree, save the coordinates//if not present, then use the coordinates///save the coordinates of the smaller elements, you can omit to consider the existence of the left and right subtrees, and only the case if (RI
                    Ghtchild <= data.size ()-1) {if (Data.get (rightchild). CompareTo (Data.get (leftchild)) < 0) {
                Minindex = Rightchild; } if (Data.get (Minindex). CompareTo (last) < 0) {Data.set parent, data.get (mi
                nindex));
                Data.set (Minindex, last);
                parent = Minindex;
                Leftchild = parent * 2 + 1;
            Rightchild = parent * 2 + 2;
    else {break;//The nature of the minimum heap has been reached} return removed; @Override Public String toString () {return data.tostring (); }

}
Reference Articles

http://bubkoo.com/2014/01/14/sort-algorithm/heap-sort/

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.