标签: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(); } }
标签:empty key bounds out following red OWIN list bool
原文地址:https://www.cnblogs.com/w-j-c/p/9136319.html