UnorderedArrayPQ

2018-03-28  本文已影响0人  賈小強

简书 賈小強
转载请注明原创出处,谢谢!

package com.lab1.test2;

public class UnorderedArrayPQ<Key extends Comparable<Key>> {
    private Key[] a = (Key[]) new Comparable[5];
    private int n;

    private boolean isEmpty() {
        return n == 0;
    }

    private int size() {
        return n;
    }

    private Key delMax() {
        int max = 0;
        for (int i = 0; i < n; i++) {
            if (less(a[max], a[i])) {
                max = i;
            }
        }
        exch(max, n - 1);
        return a[--n];
    }

    private void exch(int i, int j) {
        Key temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    private boolean less(Key v, Key w) {
        return v.compareTo(w) < 0;
    }

    private void put(Key key) {
        a[n++] = key;
    }

    public static void main(String[] args) {
        UnorderedArrayPQ<String> pq = new UnorderedArrayPQ<>();
        pq.put("bill");
        pq.put("jack");
        pq.put("lucy");
        System.out.println(pq.delMax());
        System.out.println(pq.delMax());
        System.out.println(pq.delMax());
        System.out.println(pq.size());
        System.out.println(pq.isEmpty());
    }
}

输出

lucy
jack
bill
0
true

Happy learning !!

上一篇下一篇

猜你喜欢

热点阅读