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

2.4.3

时间:2018-06-04 23:22:39      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:empty   key   bounds   out   following   red   OWIN   list   bool   

question:

Provide priority-queue implementations that support insert and remove the maximum, one for each of the following underlying data structures: unordered array, ordered array, unordered linked list, and linked list. Give a table of the worst-case bounds for each operation for each of your four implementations.

answer:

//unordered array

import edu.princeton.cs.algs4.*;

public class UnorderedArrayMaxPQ<Key extends Comparable<Key>> 
{
    private Key[] pq;
    private int N;
    
    public UnorderedArrayMaxPQ(int maxN)
    {
        pq = (Key[]) new Comparable[maxN];
        N = 0;
    }
    
    public boolean isEmpty()
    {
        return N == 0;
    }
    
    public int size()
    {
        return N; 
    }
    
    public void insert(Key x)
    {
        pq[N++] = x;
    }
    
    public Key delMax()
    {
        int max = 0;
        for(int i = 0 ; i < N; i++)
        {
            if(less(max,i))
                max = i;
        }
        exch(max, N-1);
        Key c = pq[N-1];
        N--;
        return c;
    }
    
    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;
    }
    
    public static void main(String[] args)
    {
        int N = 20;
        UnorderedArrayMaxPQ<String> pq = new UnorderedArrayMaxPQ<String>(N);
        String[] a = {"P","R","I","O","*","R","*","*","I","*","T","*","Y","*","*","*","Q","U","E","*","*","*","U","*","E"};
        for(int i = 0; i < a.length; i++)
        {
            if(a[i] == "*")
            {
                if(!pq.isEmpty())
                {
                    StdOut.print(pq.delMax() + " ");      
                }
            }
            else
                pq.insert(a[i]);
        }
        StdOut.println();
    }
}

 

2.4.3

标签:empty   key   bounds   out   following   red   OWIN   list   bool   

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

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