码迷,mamicode.com
首页 > 其他好文 > 详细

2.4.19

时间:2018-06-05 20:01:10      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:没有   oid   rabl   items   while   tom   2.4.1   show   stat   

question:

Implement the constructor for MaxPQ taht takes an array of items as argument, using the bottom-up heap construction method described on page 323 in the text.

answer:

//这里说的bottom-up其实指的就是swim(),当然这样构造堆肯定没有用sink()好

import edu.princeton.cs.algs4.*;

public class MaxPQ<Key extends Comparable<Key>>
{
    private Key[] pq;
    private int N = 0;
    
    public MaxPQ(int maxN)
    {
        pq = (Key[]) new Comparable[maxN + 1];
    }
    
    public MaxPQ(Key[] a)//就是这里
    {
        pq = (Key[]) new Comparable[a.length + 1];
        for(int i = 0; i < a.length; i++)
        {
            pq[i+1] = a[i]; 
            swim(i+1);
        }
    }
    
    public boolean isEmpty()
    {
        return N == 0;
    }
    
    public int size()
    {
        return N;
    }
    
    public void insert(Key v)
    {
        pq[++N] = v;
        swim(N);
    }
    
    public Key delMax()
    {
        Key max = pq[1];
        exch(1,N--);
        pq[N+1] = null;
        sink(1);
        return max;
    }
    
    private boolean less(int i, int j)
    {
        return pq[i].compareTo(pq[j]) < 0;
    }
    
    private void exch(int i, int j)
    {
        Key t = pq[i];
        pq[i] = pq[j];
        pq[j] = t;
    }
    
    private void swim(int k)
    {
        while(k > 1 && less(k/2,k))
        {
            exch(k/2,k);
            k/=2;
        }
    }
    
    private void sink(int k)
    {
        while(2*k <= N)
        {
            int j = 2*k;
            if(j < N && less(j,j+1)) j++;
            if(!less(k,j)) break;
            exch(k,j);
            k = j;
        }
    }
    
    private void show()
    {
        for(int i = 1; i < pq.length; i++)
            StdOut.print(pq[i] + " ");
    }
    
    public static void main(String[] args)
    {
        Integer[] a = {1,3,2,4,8,5,6,9,7};
        MaxPQ<Integer> pq = new MaxPQ<Integer>(a);
        pq.show();
    }
}

 

2.4.19

标签:没有   oid   rabl   items   while   tom   2.4.1   show   stat   

原文地址:https://www.cnblogs.com/w-j-c/p/9141375.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!