Java data structure and algorithm parsing (13)--Priority Queue __ Storage

Source: Internet
Author: User
Tags data structures
Java data structure and algorithm parsing (13)--Priority queue

In many applications, we usually need to deal with the processing object according to the priority situation, such as dealing with the highest priority object first, and then processing the object of the high level. The simplest example is when you play a game on a mobile phone, and if there is a call, then the system should prioritize incoming calls.

In this case, our data structure should provide two basic operations, one is to return the highest priority object, the other is to add a new object. This data structure is the priority queue (Priority queues). definition

Priority queues are the same as the usual stacks and queues, except that each element in it has a "priority" that is processed first with the highest priority. If two elements have the same priority, they are processed in the order they are inserted into the queue.

Priority queues can be implemented through linked lists, arrays, heaps, or other data structures.

How priority queues are implemented Array

The simplest priority queues can be implemented by an ordered or unordered array, and when the maximum value is obtained, the arrays are searched and returned.

Unordered Array Implementation
If you use a unordered array, you insert it directly at the end of the array at each insertion, and the time Complexity is O (1), but if you want to get the maximum value, or if the minimum value returns, you need to search for the time complexity of O (n).

To implement the deletion of the maximum element, you can add an inner loop code similar to the selection sort, remove the maximum element's and boundary elements, and implement the Pop () method on the stack. You can also add code to adjust the array to achieve the purpose of dynamically adjusting the array.

Ordered array implementation
If you use an ordered array, each time you insert it, by inserting the sort to place the element in the correct position, the time complexity is O (n), but if you want to get the maximum value, the time complexity is O (1) because the Ashu is ordered and the element at the end of the array is returned directly.

Add code to the Insert method to move all the larger elements to the right one to keep the array in order (as is the insertion sort). In this way, the largest element will always be on one side of the array, delete the largest element, just like the stack of Pop () on the same.

Therefore, the use of ordinary array or linked list to achieve, can not make the insertion and sorting to achieve a better time complexity. So we need a two-fork heap (binary heap) to implement priority queue list notation

We can also use the code based on the down-stack of the linked list, and then choose to modify the pop () to find and return the largest element, or to modify the push () to ensure that all elements are in reverse order and that the pop () is used to remove and return the first element of the list.
Two fork Heap

A binary heap is a structure of an approximate complete binary tree and satisfies the nature of the accumulation: the key value or index of a child node is always less than (or greater than) its parent. With this property, the maximum value on the two-fork heap is the root node.

Binary heap representation: We can use the index of the array to represent the position of the element in the binary heap.

From the two-fork heap, we can draw:

· The parent node of element K is located in [K/2]

· The location of the child nodes of element K is 2k and 2k+1

According to the rules above, we can use the index of two-dimensional arrays to represent binary heaps. Through the binary heap, we can realize the time complexity of inserting and deleting the maximum value to the O (Nlogn).

For a heap, the maximum element is already at the root node, and the deletion is to remove and return the root node element, at which point the binary heap needs to be rearranged; when inserting new elements, it is also necessary to rearrange the binary heap to satisfy the definition of the binary heap.

Ordered changes from the next highest heap
If the value of a node is greater than the value of its parent node, then the node needs to move up to meet the node greater than its two subnodes, and less than its root node, thus achieving a two-fork heap for the entire heap.

All we need to do is compare the element k to its parent element K/2, if it is larger than the parent element, then swap and then iterate until it is smaller than the parent element.

private static void swim (int k)
{
    //If the element is larger than its parent element, swap while
    (k > 1 && pq[k]. CompareTo (PQ[K/2]) > 0)
    {
        Swap (PQ, K, K/2);
        K = K/2;
    }
}
1 2 3 4 5 6 7 8 9

In this way, the operation of inserting a new element into the heap becomes, and the element is then built up from the bottom to the heap operation:

The code implementation is as follows:

public static void Insert (T s)
{
    //add element to end of array
    pq[++n] = s;
    Then let the element rebuild the heap
    swim (N) from bottom to top;
}
1 2 3 4 5 6 7

Ordered changes from top to bottom stacks
When a node is smaller than its child nodes, the definition of the two-fork heap is violated, and its child nodes are exchanged to re-create the heap until the node is greater than its child nodes:

private static void Sink (int k)
{while
    (2 * k < N)
    {
        Int j = 2 * k;
        To the left and right child nodes, the slightly larger element is compared to the
        if (pq[j). CompareTo (Pq[j + 1]) < 0) J + +;
        If the parent node is larger than this larger element, the request is satisfied and the pq[k is exited
        . CompareTo (Pq[j]) > 0) break;
        Otherwise, swap swap with child nodes
        (PQ, K, j);
        K = j;
    }
}
1 2 3 4 5 6 7 8 9 10 11 12 13-14

Thus, the removal and return of the maximum element operation Delmax can be changed to:

Removes the binary heap root node element and returns

Place the last element in the array at the root node

The new root node element is then sink to meet the binary heap requirements.

Remove the maximum value and return the operation as shown in the following illustration:

public static T Delmax ()
{
    //root element starting from 1, 0 does not store value
    T max = pq[1];
    Swap the last element and the root node element for swap
    (PQ, 1, n--);
    New Heap
    Sink (1) from top to bottom for root node;
    Place the last element as empty
    Pq[n + 1] = default (T);
    return max;
}
1 2 3 4 5 6 7 8 9 10 11-12

Multi-Fork Heap

Based on the complete tri-tree construction heap represented by arrays and modifying the corresponding code, it is not difficult to correspond to n elements 1 to n in the array, the node of position k is greater than or equal to 3k-1,3k,3k+1, and is less than the node that is rounded under [(k+1)/3]. d Fork Heap

Complete D-fork tree with minimal root. Use a sequence when storing.

The operation is basically the same as the two-fork heap: insert,deletemin, increasing elements, reducing elements, deleting non top elements, and merge.

The comparison between the two-fork heap and the D-fork Heap:

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.