2.4.3
Posted w-j-c
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2.4.3相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章