Daily ———— use a two-fork heap to implement priority queues

Source: Internet
Author: User
Tags assert comparable int size

Today, I mainly want to review the priority queue this data structure. Although the title is known as "daily One province", but the work of people involuntarily, has not been updated for many days. Haha, do not say much nonsense, directly into the business. 1 The concept of priority queues:

A precedence queue is an abstract data structure in which each element in a queue has a priority value. A priority value is used to indicate the order in which the element is aligned.
Priority queues are data structures that allow at least two operations to insert operations and delete the smallest (or largest) element. Typically, priority queues are implemented through a binary heap. 22-Fork Heap Concept:

The heap is a fully-filled two-fork tree, with the bottom exception, and the elements on the bottom are filled in sequentially from left to right. If an array is used to represent a binary heap, the left child element index of the element on the array is 2i, the index of the right child element is (2i + 1), and the parent node index is [I/2].
The nature of the heap, in which each element is guaranteed to be greater than the element equal to the other two specific positions. So, in a two-fork tree with an ordered heap, each node is less than or equal to its parent node. Therefore, the root node is the largest node in a two-fork tree with an ordered heap.
Of course, the nature of the pair can also be reversed, that is, each element is guaranteed to be less than the element equal to the other two specific positions. So, in a two-fork tree with an ordered heap, each node is greater than or equal to its parent node. Therefore, the root node is the smallest node in a two-fork tree with an ordered heap. 3 code example for priority queues using two-fork heap implementations

Import Java.util.Comparator;
Import Java.util.Iterator;

Import java.util.NoSuchElementException; public class Maxfirstqueue<t> implements iterable<t> {private t[] queue;//China The underlying implementation of the priority queue is a two-fork heap, and the binary heap is used as an array to table Shows private int size = 0; Represents the number of elements in a queue, not the capacity to represent an array private comparator<t> Comparator;
    An optional comparer that can be passed into the public maxfirstqueue (int max) {queue = (t[]) new Comparable[max + 1] As the constructor parameter of the class;
    Public Maxfirstqueue () {this (1);
        Public maxfirstqueue (int initcapacity, comparator<t> Comparator) {this.comparator = Comparator;
        Queue = (t[]) new Object[initcapacity + 1];
    size = 0;
    Public Maxfirstqueue (comparator<t> Comparator) {This (1, Comparator);
        Public Maxfirstqueue (t[] values) {size = Values.length;
        Queue = (t[]) new Object[values.length + 1];
        for (int i = 0; i < size; i++) {//The binary heap is represented by an array, the position of the array index 0 does not hold the element, and the position element value is always empty    Queue[i + 1] = values[i];
        for (int k = SIZE/2 k >= 1; k--) {sinkdown (k);
    Assert Isvalidheap ();
    public int size () {return size;
    public Boolean IsEmpty () {return size = = 0; } * * Determines whether the two-fork heap of all elements in array queue satisfies the basic nature of the binary heap, that is, the parent node element is the largest, and then each child node is larger than the sub node below it. * Private Boolean Isvalidheap ()
    {return isvalidsubheap (1); } * * Determines whether the child heap with the queue[k] position is satisfied with the basic nature of the binary heap: The parent node (the parent node is queue[k]) element is the largest, * and then each child node is larger than the sub node below it/private boo
        Lean isvalidsubheap (int k) {if (k > size) {return true;
        int left = 2 * k, right = 2 * k + 1;
        if (left <= size && less (k, left)) {return false;
        } if (right <= size && less (k. right)) {return false;
    Return to Isvalidsubheap (left) && isvalidsubheap (right); /** * Remove Maximum/public T mAx () {if (IsEmpty ()) {throw new Nosuchelementexception ("The priority queue that can fetch the maximum element each time is empty and no elements are stored therein");
    return queue[1]; /** * Insert element */public void Add (T value) {if (size >= queue.length-1) {Resiz
        E (2 * queue.length);
        } Queue[++size] = value;
        Swimup (size);
    Assert Isvalidheap ();
     /** * After deleting an element, it actually places the deleted element where the index is size (and then sets the position element value to null), which cannot be counted as part of the two-fork heap.  * The size of the binary heap becomes size--* * * The following three lines of code can be written together as Exchange (1, size--), Queue[size + 1] = null, and this three lines of code are as follows: * Exchange (1, size); Queue[size] = null;
     size--; */Public T Deletemax () {if (IsEmpty ()) {throw new Nosuchelementexception ("The priority queue that can fetch the maximum element each time is empty, no
        There are any elements stored therein ");
        } T value = Queue[1];
        Exchange (1, size);
        Queue[size] = null;
        size--;
        Sinkdown (1); if (Size > 0) && (size = = (queue.length-1)/4)) {Resize (quEUE.LENGTH/2);
        Assert Isvalidheap ();
    return value;
     * * * Adjust the size of the underlying array: by creating a temporary array of the specified size, and then moving the elements in the queue to the appropriate location of the temporary array, * Finally set the temporary array as the underlying implementation of the precedence queue.
        * * private void resize (int capacity) {assert capacity > size;
        t[] temp = (t[]) new object[capacity];
        for (int i = 1; I <= size; i++) {temp[i] = Queue[i];
    } queue = temp; Private Boolean less (int i, int j) {if (comparator = = null) {return (comparable<t>) Qu
        Eue[i]). CompareTo (Queue[j]) < 0;
        else {return Comparator.compare (Queue[i], Queue[j]) < 0;
        } private void Exchange (int i, int j) {T temp = queue[i];
        Queue[i] = Queue[j];
    QUEUE[J] = temp; * * * The element value is greater than the parent node's child node and the parent node swap position, keeping the heap in order. After the swap position, the original child node may still be larger than the parent node on the upper level, so the whole process needs to be recursive.
     As a result, the original child nodes may be upgraded to a higher level of parent nodes, similar to the process by which an object floats from the bottom of the lake until it reaches its gravitational and buoyancy equilibrium. * * private void Swimup (int k) {while (K > 1 && less (K/2, K)) {Exchange (k, K/2);
        K = K/2; }/* * The element value is less than the parent node of the child node and the child node swap position, the original parent node may still be smaller than the child nodes below it, * so it is necessary to continue the same operation of the class in order to maintain the order of the heap.
     So the whole process is recursive.
     * This is analogous to an object sinking from the lake to a place near the bottom of the lake until its gravity and buoyancy are balanced.
            * * private void Sinkdown (int k) {while (2 * k <= size) {int J = 2 * k;
            if (J < size && less (J, j + 1)) {j + +;
            } if (!less (k, J)) {break;
            Exchange (k, j);
        K = J;
    @Override public iterator<t> iterator () {return new maxfirstqueueiterator ();

        /** * The specific implementation of the iterator for traversing the elements in the precedence queue:/Private class Maxfirstqueueiterator implements Iterator<t> {
         /* * Equivalent to a copy of the priority queue being iterated, traversing the elements in the precedence queue is actually a copy of it, * so, in a multithreaded environment, concurrent additions, deletions, traversal elements can cause data confusion. * Private maxfirstqueue<t> Copy; Public Maxfirstqueueiterator () {if (comparator = = null) {copy = new maxfirstqueue<t> (s
            Ize ());
            else {copy = new maxfirstqueue<t> (size (), comparator);
        for (int i = 1; I <= size; i++) Copy.add (queue[i));
        public Boolean Hasnext () {return!copy.isempty ();
        The public void Remove () {throw new Unsupportedoperationexception ("Iterator does not support removal operations");
            Public T Next () {if (!hasnext ()) {throw new nosuchelementexception ();
        return Copy.deletemax (); }/** * Main method: Contains test code */public static void main (string[] args) {MAXFIRSTQUEUE&LT;STRING&G T
        PQ = new maxfirstqueue<string> ();
        Pq.add ("S");
        Pq.add ("T");
       System.out.println ("===================================================="); for (String e:pq) {System.out.println (e);
        } pq.add ("C");
        Pq.add ("A");
        Pq.add ("M");
        Pq.add ("B");
        System.out.println ("====================================================");
        for (String e:pq) {System.out.println (e);
        } System.out.println ("====================================================");
        Iterator<string> iterator = Pq.iterator ();
        Iterator.foreachremaining (t-> System.out.print ("-" + t + "-"));
        System.out.println ();
        System.out.println ("====================================================");
            try {System.out.println (Pq.deletemax ());
            System.out.println (Pq.deletemax ());
            System.out.println (Pq.deletemax ());
            System.out.println (Pq.deletemax ());
            System.out.println (Pq.deletemax ());
            System.out.println (Pq.deletemax ());
        System.out.println (Pq.deletemax ());The catch (Exception e) {System.out.println ("queue is empty, size is" + pq.size);
        } pq.add ("C");
        Pq.add ("A");
        Pq.add ("M");
        Pq.add ("B");

    System.out.println ("Queue size is" + pq.size);


 }

}

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.