Collection and map in Java (v)--priorityqueue

Source: Internet
Author: User
Tags comparable

Priorityqueue the Java API gives the definition:

A queue of unbounded priorities based on the priority heap. The elements of the priority queue are sorted in their natural order, or sorted according to the construction method that is provided when the queue is constructed Comparator , depending on the constructor used. The priority queue does not allow the use of null elements. Priority queues that rely on natural order also do not allow the insertion of objects that cannot be compared (this can be caused ClassCastException ).

The header of this queue is the smallest element determined by the specified sort. If more than one element is the minimum, the header is one of the elements-the selection method is arbitrary. The queue gets poll operations remove , peek and element accesses elements that are in the queue header.

The priority queue is unbounded, but has an internal capacity that controls the size of the array used to store the queue elements. It is usually at least equal to the size of the queue. As you continue to add elements to the priority queue, their capacity increases automatically. You do not need to specify the details of the capacity increase policy.

This class and its iterators implement all the Collection optional Iterator methods of the and interface. iterator()the iterators provided in the method do not guarantee that the elements in the priority queue are traversed in any particular order. If you need to traverse sequentially, consider using Arrays.sort(pq.toArray()) .

Note that this implementation is not synchronous. if any thread in multiple threads modifies the queue, those threads should not access the instance at the same time PriorityQueue . Instead, use a thread-safe PriorityBlockingQueue class.

Implementation considerations: This implementation provides an O (log (n)) time for the queued and outbound methods ( offer , poll , and), a remove() add linear time for the and methods, and a remove(Object) contains(Object) fixed time for obtaining methods ( peek , element and size ).

This class is a member of the Java collections Framework.

In the usual programming work seems to encounter Priorityqueue (priority queue), so many people start to see the priority queue is a bit confusing. A priority queue is essentially a minimal heap. What the heap is, we can understand that he is an array, but satisfies the special nature. We look at this array in a completely binary tree perspective and map it to the array with the subordinate relationship of the binary tree. If it is the largest heap, then the vertex of the two-fork tree is the maximum value saved, and the minimum heap is the minimum value saved.

Priorityqueue Method of Construction:

   

Java provides us with multiple construction methods, and when we want Priorityqueue to be combined, there is a process for priorityqueue the heap (by calling the Heapify () method):

private void Heapify () {for (int i = (size >>> 1)-1; I >= 0; i--) siftdown (i, (E) queue[i    ]);        } private void Siftdown (int k, E x) {if (comparator! = null) Siftdownusingcomparator (k, x);    Else Siftdowncomparable (k, x);        }private void Siftdownusingcomparator (int k, E x) {int half = size >>> 1;            while (K < half) {Int. Child = (k << 1) + 1;            Object C = Queue[child];            int right = child + 1; if (Right < size && Comparator.compare ((e) C, (e) queue[right]) > 0) c = Queue            [child = right];            if (Comparator.compare (x, (E) c) <= 0) break;            QUEUE[K] = c;        K = child;    } Queue[k] = x;        }private void siftdowncomparable (int k, E x) {comparable<? super e> key = (comparable<? super e>) x;        int half = size >>> 1; LOop while a non-leaf when (K < half) {int child = (k << 1) + 1;//Assume left child is least            Object C = Queue[child];            int right = child + 1;                if (Right < size && (COMPARABLE&LT;? Super E>) c). CompareTo ((E) queue[right]) > 0)            c = Queue[child = right];            if (Key.compareto ((E) c) <= 0) break;            QUEUE[K] = c;        K = child;    } Queue[k] = key; }

We represent the structure of the underlying array in the form of a tree:

Suppose we initialize with such a set of data [8,5,7,9,6,1], the corresponding tree structure is as follows:

The first step is to adjust:

  

Second Step adjustment:

  

Third-Step adjustment:

  

Follow the previous procedure and believe that the code is well understood.

Priorityqueue the underlying use of arrays to store data, which is the same as ArrayList will be involved in the expansion of the problem, we see how priorityqueue is expanding.

private void Grow (int mincapacity) {        int oldcapacity = queue.length;        Double size if small; else grow by 50%        int newcapacity = oldcapacity + ((Oldcapacity <)?                                         (Oldcapacity + 2):                                         (oldcapacity >> 1));        Overflow-conscious Code        if (newcapacity-max_array_size > 0)            newcapacity = hugecapacity (mincapacity);        Queue = arrays.copyof (queue, newcapacity);    }    private static int hugecapacity (int mincapacity) {        if (mincapacity < 0)//overflow            throw new Outofmemoryerro R ();        Return (Mincapacity > max_array_size)?            Integer.max_value:            max_array_size;    }

This part of the code is basically the same as the internal implementation Code of ArrayList, which is to find the appropriate array length first, and then copy the elements from the old array to the new array.

Add (E) method:

Public boolean Add (E-e) {        return offer (e);    } Public Boolean offer (E e) {        if (E = = null)            throw new NullPointerException ();        modcount++;        int i = size;        if (i >= queue.length)            Grow (i + 1);        size = i + 1;        if (i = = 0)            queue[0] = e;        else            Siftup (i, e);        return true;    }

From this code we can see that priorityqueue, NULL is not supported and the real implementation when adding is the Siftup method:

private void Siftup (int k, E x) {if (comparator! = null) Siftupusi        Ngcomparator (k, x);    Else Siftupcomparable (k, x);         } private void Siftupcomparable (int k, E x) {comparable<? super e> key = (comparable<? super e>) x;            while (k > 0) {int parent = (k-1) >>> 1;            Object e = queue[parent];            if (Key.compareto (e) e) >= 0) break;            Queue[k] = e;        K = parent;    } Queue[k] = key; } private void Siftupusingcomparator (int k, E x) {while (K > 0) {int parent = (k-1) >>&G T            1;            Object e = queue[parent];            if (Comparator.compare (x, (e) e) >= 0) break;            Queue[k] = e;        K = parent;    } Queue[k] = x; }

If we initialize the Priorityqueue is empty, we also use [8,5,7,9,6,1] This data, call Priorityqueue's Add (e) method, we look at their specific process. A tree-shaped structure is also used to describe this.

The first call to the Add (e) method E=8, after the data result is [8];

The second call to the Add (e-E) method E=5, after the data result is [5,8];

The third call to the Add (e-E) method e=7, after the data result is [5,8,7];

The fourth call to the Add (e) method E=9, after the data result is [5,8,7,9];

The fifth call to the Add (e) method E=5, after the data result is [5,6,7,9,8];

The sixth call to the Add (e) method e=1, after the data result is [1,6,5,9,8,7];

The final tree structure is as follows:

  

Note: We look at the previous adjustment method whether it is Siftup or Siftdown have used two methods, one is used comparator, there is a default comparison results. The purpose of this is to take into account that the elements we are comparing are not just types of numbers, but also possible to define comparable data types. For custom data types, their size comparison definition requires implementation of the comparator interface.

Collection and map in Java (v)--priorityqueue

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.