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.

  • 相关阅读:
    在rhel6上安装Python 2.7和Python 3.3
    RHEL7 -- Linux搭建FTP虚拟用户
    RHCE7 -- IPv6
    RHEL7 -- nmcli的使用
    设置Adobe Reader打开PDF文件保持记忆功能
    iptalbes -F
    服务器IP地址后修改SQL Server配置
    配置SELINUX
    11G新特性 -- 分区表和增量统计信息
    11G新特性 -- Statistics Preferences
  • 原文地址:https://www.cnblogs.com/ssMellon/p/6558472.html
Copyright © 2011-2022 走看看