-10- priority queue algorithm

table of Contents

1. Background

2, priority queue

3, binary heap

4, the insertion function -insert ()

5, remove the largest element - delMax ()

6, the complete code

7, trigeminal tree


1. Background

Consider the following questions: Enter the value of N int, find out the maximum (or minimum) M a int value. In this scenario may appear: There are many such bills monthly record, I only need to consume a maximum of 5 records. So what we achieve this is it?

Method a: int these values ​​of N sorted, and then sequentially outputs the M largest. (If large amounts of data, you have to wait until after each finished sorting in order to get the value you want, you can not be immediately)

Method two: every time a new spending record inserted, and that both M (5) pen's largest record for comparison. (M is very small unless otherwise is costly)

Method three: the priority queue (the maximum insertion of the element has been placed on a suitable location, waiting to acquire)

2, priority queue

Priority queue is an abstract data type, and stacks and queues similar, but not the same functions.

Its main functions are: 1, delete (get) the largest element;

                             2, insert elements

Insert and delete elements to achieve in three ways:

The first is the insertion sort when he is good, so take the time to take a direct enough. (Ordered array)

The second is the insertion of the matter, take the time to get the maximum traversing elements. (Unordered array)

The third is a binary heap. Here are three time complexity.

3, binary heap

Binary heap is a special stack, is perfectly binary heap dual tree (binary) or almost completely dual tree (binary tree). There are two binary heap: the greatest heap and minimum heap . Max heap: parent node key is always greater than or equal to any one sub- node keys; minimum heap: parent node is always less than or equal to any key a key child nodes.

Usually a binary heap array represented. If the root array is in position 1, the n sub-node positions, respectively 2 n and 2 n + 1'd. Thus, the first position of the sub-nodes 2 and 3, the second position of the sub-nodes 4 and 5. And so on. Such a storage array based easy to find the parent and child nodes.

FIG under a [1] child node is a [2] and a [3].

                                                     

4, the insertion function -insert ()

Insert an element, we will put it on the end of the array, and then find the index of its parent node according to k / 2, and the comparison and, if greater than a [k / 2], then put the parent replace node down. So that we can ensure that the root of a [1] (a [0] is not used) is always the biggest element.

                               

5, remove the largest element - delMax ()

We delete the last element of the array elements and the largest array from the top into the top, to reduce the size of the heap and let this sink element to the appropriate location.

              

6, the complete code

public class MaxPQ {

    private static double[] a;
    private static int N = 0;

    private MaxPQ(int lenght) {
        a = new double[lenght + 1];
    }
    public void insert(double item) {
        a[++N] = item;
        swim(N);
    }
    /**
     * 删除堆中最大的元素
     */
    public double delMax() {
        double maxItem = a[1];
        a[1] = a[N--];// 先拿到a[N]元素之后,N才会减一
        a[N+1] = 0; // 如果这里是对象的话,可以用来置空释放对象的引用,防止对象游离
        sink(1);// 将新的根结点,下沉到合适位置,堆的重新排序

        return maxItem;
    }
    /**
     * 上浮
     */
    private void swim(int k) {

        while (k > 1) {
            if (a[k] > a[k / 2]) {
                exch(k, k / 2);// k/2获取到它的父结点
                k = k / 2;
            } else {
                break;
            }
        }
    }
    /**
     * 下沉
     */
    private void sink(int k) {

        while (2 * k <= N) {
            int j=2*k;
            if (j<N&&a[j]<a[j+1]) j++; //保证每次和a[k]比较的是它的两个子结点中较大的那个

            if (a[k]>a[j])break;

            exch(k,j);
            k=j;
        }
    }
    private void exch(int i, int j) {
        double temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
    public static double[] getA() {
        return a;
    }
    private static void show(double[] a) {
        System.out.println("\n");
        for (double item : a) {
            System.out.print((int) item + ",");
        }
    }
    public static void main(String[] args) {
        double[] a = { 55, 43, 23, 12, 13, 11, 7, 8, 88, 6, 3, 2, 4, 1, 9, 8, 7, 11, 56, 45, 22, 23,
                45, 66 };

        MaxPQ maxPQ = new MaxPQ(a.length);
        for (double item : a) {
            maxPQ.insert(item);
        }
        
        show(getA());
        for (int i=0;i<a.length;i++){
            maxPQ.delMax();
            show(getA());
        }
    }
}

7, trigeminal tree

Our top priority queue code is the use of the form to achieve complete binary tree, then we can not use ternary tree or more trees to achieve the priority queue it?

Ternary tree parent node is located (k + 1) / 3 position, the child nodes located 3k-1,3k, 3k + 1 position. Our major changes to the code that is floating and sinking code. The code change follows :( according to implement the following code, we can achieve in the form of multi-tree, not enough pros and cons of performance have to go test)

    /**
     * 上浮
     */
    private void swim(int k) {
        while (k > 1) {
            if (a[k] > a[(k+1) / 3]) {
                exch(k, (k+1) / 3);// k/2获取到它的父结点
                k = (k+1) / 3;
            } else {
                break;
            }
        }
    }
    /**
     * 下沉
     */
    private void sink(int k) {
        int max;
        while ( (3*k-1) <= N) {
            int j=3*k-1;
            max=j;
            while (j<3*k+1&&j<N) {//保证每次和a[k]比较的是它的两个子结点中较大的那个
                if (a[j] < a[j+1]) max=j+1;
                j++;
            }
            if (a[k]>a[max])break;

            exch(k,max);
            k=max;
        }
    }

 

 

 

 

 

 

Published 82 original articles · won praise 16 · views 260 000 +

Guess you like

Origin blog.csdn.net/qq_34589749/article/details/104054694