zoukankan      html  css  js  c++  java
  • Prior queue

    Introduction:usually,we tend to insert a new value into a container and get a min or max value from the container,if the input frequency and the output frequency are about the same ,then we may construct a contanier with average less operation time.we can use the heap structure,it's a compelete binary tree.

    so firstly we may see the usual operation:

    constructed function:

    public IntMinPQ(){elements=new Integer[1];elements[0]=Integer.MAX_VALUE;}
    public IntMinPQ(int max){maxSize=max+1;elements=new Integer[maxSize];elements[0]=Integer.MAX_VALUE;}
    public IntMinPQ(Integer[]a){
    int len=a.length;
    maxSize=len+1;
    elements=new Integer[maxSize];
    elements[0]=Integer.MAX_VALUE;
    for(int i=0;i<len;++i){
    insert(a[i]);
    }
    }

    then the often used functions:

    public void insert(Integer v){
    if(size<maxSize){
    elements[++size]=v;
    }
    swimUpdate(size);
    }
    public Integer min(){return elements[1];}
    public Integer delMin(){
    Integer temp=elements[1];
    percolateDown();
    return temp;
    }
    public boolean isEmpty(){return size==0;}
    public int size(){return size;}

    In the above functions there are some assistant fucntions:

    In order to get a value from the container with O(log(N)) time , we need a insert fucntion to keep the insert time:

    private void swim(int k){
    while(k>1){
    if(less(k,k/2)){
    swap(k,k/2);
    }else{
    break;
    }
    k/=2;
    }
    }

    also we need a function to keep the get time with O(log(N)) time:

    private void percolateDown(){
    int index=1;
    while(2*index<size){
    if(less(2*index,2*index+1)){
    elements[index]=elements[2*index];
    index=2*index;
    }else{
    elements[index]=elements[2*index+1];
    index=2*index+1;
    }
    }
    elements[index]=elements[size];
    elements[size]=null;
    --size;
    }
    the problem is how to handle with the last element,the function given above is called
    percolateDown(),just as its name implies:the element with less value is jump down step by step.

    besides that ,some inner variables are also needed: 

    private Integer[] elements=null;
    private int size=0;
    private int maxSize=0;

    The end.

  • 相关阅读:
    java 06 作业代码
    java 06 abstract 抽象类
    java 06 重写(覆盖) final 内部类
    java 06 重写和final
    java 06 继承
    java 05 this static构造函数
    java 05 构造函数-构造代码块
    java 05 heap satck 堆和栈
    java 05 成员变量和成员函数-封装
    BJFU-207-基于顺序存储结构的图书信息表的逆序存储
  • 原文地址:https://www.cnblogs.com/ssMellon/p/6558472.html
Copyright © 2011-2022 走看看