Discussion on algorithm and data structure: five-priority queue and heap sort __java

Source: Internet
Author: User
Tags arrays data structures sort

In many applications, we often need to handle processing objects in priority situations, such as first processing the highest-priority objects, and then processing the objects with the secondary height. One of the simplest examples is when you play a game on your phone, if you have a call, the system should prioritize the incoming calls.

In this case, our data structure should provide two of the most basic operations, one is to return the highest priority object, and the other is to add a new object. This data structure is the priority queue.

This paper first introduces the definition of priority queue, ordered and unordered arrays, and the implementation of priority queue for heap data structure, and finally introduces the definition of heap sort based on priority queue.

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

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

The simplest priority queue can be implemented by an ordered or unordered array, and when the maximum value is obtained, a lookup is returned to the array. The code is relatively simple to implement, and it's not listed here.

As shown above:

· If an unordered array is used, then each time it is inserted, it is inserted directly at the end of the array, with a time complexity of O (1), but if the maximum value is to be obtained, or if the minimum value is returned, a lookup is required, and the time complexity is O (n).

· If you use an ordered array, then each time you insert, the element is placed in the correct position by inserting the order, the time complexity is O (n), but if you want to get the maximum value, because the meta-ASO is ordered, the elements at the end of the array are returned directly, so the time complexity is O (1).

Therefore, the use of ordinary arrays or linked list implementation, can not make the insertion and sorting to achieve a relatively good time complexity. So we need to adopt a new data structure to implement. Here's how to implement a priority queue two fork heap using a binary heap

A binary heap is a structure that approximates a complete binary tree and satisfies the properties of the heap at the same time: that is, the key value or index of the child node is always less than (or greater than) its parent node. With this property, the maximum value on a two-fork heap is the root node.

The expression of the binary heap: 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 conclude that:

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

· The child nodes of element K are located at 2k and 2k+1

According to the above rule, we can use the index of the two-dimensional array to represent the binary heap. Through the binary heap, we can achieve the insertion and deletion of the maximum value of O (NLOGN) time complexity.

For a heap, the largest element is already at the root node, then the delete operation is to remove and return the root node element, the binary heap needs to be rearranged, and when the new element is inserted, the binary heap needs to be rearranged to meet the definition of the binary heap. Now look at both of these operations.

Rebuild heap operations from the bottom: if the value of a node is greater than the value of its parent node, then the node needs to move up, until it satisfies the node is greater than its two child nodes, and is less than its root node, so that the entire heap is achieved two fork heap requirements.

As can be seen from the figure above, we only need to compare the element K with its parent element K/2, if it is larger than the parent element, then swap and 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;
    }
}

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

The code is implemented as follows:

public static void Insert (T s)
{
    //add element to the end of the array
    pq[++n] = s;
    Then let the element rebuild heap
    Swim (N) from bottom to top;
}

The animations are as follows:

Rebuild from top to bottom: When a node is smaller than its child node, it violates the definition of a two fork heap and needs to be swapped with its child nodes to re-create the heap until the node is larger than its child nodes:

The code is implemented as follows:

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
        if (pq[j]. CompareTo (Pq[j + 1]) < 0) J + +;
        If the parent node is larger than this larger element, indicating that the requirement is met, exit if
        (Pq[k]. CompareTo (Pq[j]) > 0) break;
        Otherwise, swap
        swap (PQ, K, J) with the child nodes;
        K = j;
    }
}

Thus, removing and returning the maximum element operation Delmax can be changed to:

1. Remove the binary heap root node element and return

2. Place the last element in the array at the root node

3. Then sink the new root node elements until the binary heap requirements are met.

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

The above actions are implemented as follows:

public static T Delmax ()
{
    //root element starting from 1, 0 does not hold value
    T max = pq[1];
    Swap the last element with the root node element
    (PQ, 1, n--);
    New Heap
    Sink (1) from top to bottom of root node;
    Set the last element to null
    Pq[n + 1] = default (T);
    return max;
}

The animations are as follows:

three stacks of sort

Concept

Using the properties of the binary heap, it can be used to sort in-place, the steps of this sort are:

1. Use all elements of the sequence to create a maximum heap.

2. Then delete the largest element repeatedly.

As an example, in order to sort s O R T e X A M P L E, the first local construction of a maximum heap, that is, the node sink operation, so that it conforms to the nature of the binary heap.

Then delete the root node again, which is the largest element, similar to the delete element of the previous two-fork heap.

To create the maximum binary heap:

The method of creating a two-fork heap using a down-to-bottom method is to reconstruct the heap from the upper node of the leaf node in a way that is heavily down.

The code is as follows:

for (int k = N/2; k >= 1; k--)
{
    Sink (PQ, K, N);
}

Sort

The use of binary heap sorting is actually a loop to remove the top element to the end of the array, and then use sink to rebuild the heap operation. The following diagram implements the code as follows:

while (N > 1)
{
    Swap (PQ, 1, n--);
    Sink (PQ, 1, N);
}

The heap sort animations are as follows:

Analysis

1. Up to 2N comparisons and exchanges are required when building the maximum heap

2. Heap sorting requires up to 2NlgN comparison and exchange operations

Pros: The most significant advantage of heap sequencing is that he is in-place sort, and the worst-case time complexity is nlogn. The classic merge sort is not an in-place sort, it requires extra space for a linear length, and a quick sort of its worst time complexity is N2

Cons: Heap sequencing optimizes both time and space, but:

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.