java版数据结构与算法—堆、堆排序

优先级队列:用有序数组实现,删除最大数最快O(1),插入最慢
用堆实现优先级队列,插入和删除都很快O(logN)
堆:是一种树,一种特殊的二叉树
特点:
1.他是完全的二叉树,除了树的最后一层节点不需要是满的,其他一层从左到右都是满的。
2.它常常用一个数组实现。
3.堆中每一个节点都满足堆的条件,父节点的关键字要大于所有子节点。
堆是弱序,(接近没有排序,不支持遍历),最大好处,快速移除最大节点,快速插入一个新节点。做优先级队列很合适。

package com.zoujc.heap;

/**
 * 堆排序
 */
public class Node {
    private int iData;
    public Node(int key){
        iData = key;
    }
    public int getKey(){
        return iData;
    }
    public void setKey(int id){
        iData = id;
    }
}
class Heap{
    private Node[] heapArray;
    private int maxSize;
    private int currentSize;
    public Heap(int mx){
        maxSize = mx;
        currentSize = 0;
        heapArray = new Node[maxSize];
    }
    public boolean isEmpty(){
        return currentSize == 0;
    }
    public void insertAt(int index,Node newNode){
        heapArray[index] = newNode;
    }
    public void incrementSize(){
        currentSize ++;
    }
    public Node remove(){
        Node root = heapArray[0];
        heapArray[0] = heapArray[--currentSize];
        trickleDown(0); //向下调整
        return root;
    }
    //向下调整
    public void trickleDown(int index){
        int largerChild;
        Node top = heapArray[index];
        while (index < currentSize/2){
            int leftChild = 2*index+1;
            int rightChild = leftChild + 1;
            if(rightChild < currentSize && heapArray[leftChild].getKey()<heapArray[rightChild].getKey()){
                largerChild = rightChild;
            }else {
                largerChild = leftChild;
            }
            if(top.getKey() >= heapArray[largerChild].getKey()){
                break;
            }
            heapArray[index] = heapArray[largerChild];
            index = largerChild;
        }
        heapArray[index] = top;
    }
    //树状显示
    public void displyHeap(){
        int nBlanks = 32;
        int itemsPerRow = 1;
        int column = 0;
        int j = 0;
        String dots = "··················";
        System.out.println(dots + dots);
        while (currentSize > 0){
            if(column == 0){
                for(int k=0;k<nBlanks;k++){
                    System.out.print(" ");
                }
            }
            System.out.print(heapArray[j].getKey());
            if(++j == currentSize){
                break;//显示完毕
            }
            if(++column == itemsPerRow){
                nBlanks/=2;
                itemsPerRow*=2;
                column = 0;
                System.out.println();
            }else {
                for(int k = 0;k<nBlanks*2-2;k++){
                    System.out.print(" ");
                }
            }
        }
        System.out.println("\n"+dots+dots);
    }
    //按数组方式显示
    public void displayArray(){
        for(int j = 0;j<maxSize;j++){
            System.out.print(heapArray[j].getKey() + " ");
        }
        System.out.println();
    }
}






















猜你喜欢

转载自blog.csdn.net/weixin_38799368/article/details/84594005