简体   繁体   English

Java-我的二进制堆实现有多好?

[英]Java - How good is my implementation of a binary heap?

I've read a little about binary heaps/priority queues and decided to try my hand at making my own implementation of one. 我已经阅读了一些有关二进制堆/优先级队列的知识,并决定尝试自己编写一个实现。 I'm not the most experienced programmer and I would be really grateful if you guys could take a look at my heap class and tell me if it's a good implementation. 我不是最有经验的程序员,如果你们能看一下我的堆类并告诉我它是否是一个很好的实现,我将不胜感激。

What can I improve here? 我在这里可以改善什么? Any feedback is welcome. 欢迎任何反馈。

public class Heap<T extends Comparable<? super T>> {

    private T[] array = (T[])new Comparable[10];
    private int size = 0;

    public void insert(T data) {
        if(size+1 > array.length) expandArray();

        array[size++] = data;
        int pos = size-1;
        T temp;

        while(pos != 0 && array[pos].compareTo(array[pos/2]) < 0) {
            temp = array[pos/2];
            array[pos/2] = array[pos];
            array[pos] = temp;
            pos /= 2;
        }
    }

    public T deleteMin() {
        T min = array[0];

        array[0] = array[size-1];
        array[size-1] = null;
        size--;
        int pos = 0;
        T temp;
        boolean done = false;

        while(pos*2+1 < size && !done) {
            int minChild = pos*2+1;
            if(array[minChild].compareTo(array[pos*2+2]) > 0) minChild = pos*2+2;

            if(array[pos].compareTo(array[minChild]) > 0) {
                temp = array[minChild];
                array[minChild] = array[pos];
                array[pos] = temp;
                pos = minChild;
            }
            else done = true;
        }

        return min;
    }

    private void expandArray() {
        T[] newArray = (T[])new Comparable[array.length*2];

        for(int i = 0; i < array.length; i++)
            newArray[i] = array[i];

        array = newArray;
    }
}

The best way to answer your question is to write unit tests to test that your implementation is reliable, and to write some performance tests to test that your implementation is reasonably fast. 回答问题的最佳方法是编写单元测试以测试您的实现是否可靠,并编写一些性能测试以测试您的实现是否相当快。 In the process of doing those two things, you'll also find out if your implementation is easy to use. 在做这两件事的过程中,您还将发现实现是否易于使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM