Java-数据结构-大顶堆

小顶堆

大顶堆和小顶堆基本相同,只是一些比较的符号不同。

代码


/**
 * 大顶堆
 * 应用:从n个数据中找最小的m个数字
 */
public class MaxHeap {
    private static final  int  DEFAULT_INITIAL_CAPACITY = 10;
    private int currentSize;
    private int capacity;
    private int[] queue;

    public MaxHeap()
    {
        initHeap(DEFAULT_INITIAL_CAPACITY);
    }
    public MaxHeap(int capacity)
    {
        if(capacity<1||capacity>Integer.MAX_VALUE)
            throw new IndexOutOfBoundsException("非法长度");
        initHeap(capacity);
    }


    private void initHeap(int initCapacity)
    {
        this.capacity = initCapacity;
        queue = new int[initCapacity];
        currentSize = 0;
    }


    public void add(int x)
    {
        if(currentSize==0)
        {
            queue[currentSize++] = x;
        }else if(!isFull())
        {
            adjustUP(currentSize++,x);
        }
        else {
            if(x<getTop())
            {
                remove();
                add(x);
            }
        }
    }

    public boolean isFull()
    {
        return currentSize>=capacity;
    }

    public int getTop()
    {
        return queue[0];
    }
    public int remove()
    {
        int cur = getTop();
        int temp = queue[--currentSize];
        queue[0] = temp;
        adjustDown(0,temp);
        return cur;
    }
    private void adjustUP(int k,int value)
    {
        while(k>0)
        {
            int root = (k-1)>>>1;
            if(queue[root]>=value)
            {
                break;
            }
            queue[k] = queue[root];
            k = root;
        }
        queue[k] = value;
    }

    private void adjustDown(int k,int vale)
    {
        int half = currentSize>>>1;
        while (k<half)
        {
            int child = (k<<1)+1;
            int childVal = queue[child];
            int RightChild = child+1;
            if(RightChild<currentSize && childVal>queue[RightChild])
            {
                childVal = queue[child = RightChild];
            }
            if(childVal<vale)
            {
                break;
            }
            queue[k] = queue[child];
            k = child;
        }
        queue[k] = vale;
    }

    public void print()
    {
        for (int i = 0; i < currentSize; i++) {
            System.out.print(queue[i]+" ");
        }
        System.out.println();
    }

    public void add(int[] a)
    {
        for (int i = 0; i < a.length; i++) {
            add(a[i]);
        }
    }


}

猜你喜欢

转载自blog.csdn.net/qq_38345606/article/details/80951648