1. 程式人生 > >打印二叉堆(Java實現)

打印二叉堆(Java實現)

排序 item print images ray lines 堆排序 swa compare

打印二叉堆:利用層級關系

技術分享圖片

我這裏是先將堆排序,然後在sort裏執行了打印堆的方法printAsTree()

public class MaxHeap<T extends Comparable<? super T>> {
    private T[] data;
    private int size;
    private int capacity;

    public MaxHeap(int capacity) {
        this.capacity = capacity;
        this.size = 0;
        this.data = (T[]) new Comparable[capacity + 1];
    }

    public MaxHeap(T[] arr) {//heapify,數組建堆
        capacity = arr.length;
        data = (T[]) new Comparable[capacity + 1];
        System.arraycopy(arr, 0, data, 1, arr.length);
        size = arr.length;
        for (int i = size / 2; i >= 1; i--) {
            shiftDown(i);
        }
    }

    public int size() {
        return this.size;
    }

    public int getCapacity() {
        return this.capacity;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public T seekMax() {
        return data[1];
    }

    public void swap(int i, int j) {
        if (i != j) {
            T temp = data[i];
            data[i] = data[j];
            data[j] = temp;
        }
    }

    public void insert(T item) {
        size++;
        data[size] = item;
        shiftUp(size);
    }

    public T popMax() {
        swap(1, size--);
        shiftDown(1);
        return data[size + 1];
    }

    public void shiftUp(int child) {
        while (child > 1 && data[child].compareTo(data[child / 2]) > 0) {
            swap(child, child / 2);
            child /= 2;
        }
    }

    /**
     * @param a data數組中某個元素的下角標
     * @param b data數組中某個元素的下角標
     * @return 哪個元素大就返回哪個的下角標
     */
    private int max(int a, int b) {
        if (data[a].compareTo(data[b]) < 0) {//如果data[b]大
            return b;//返回b
        } else {//如果data[a]大
            return a;//返回a
        }
    }

    /**
     * @param a data數組中某個元素的下角標
     * @param b data數組中某個元素的下角標
     * @param c data數組中某個元素的下角標
     * @return 哪個元素大就返回哪個的下角標
     */
    private int max(int a, int b, int c) {
        int biggest = max(a, b);
        biggest = max(biggest, c);
        return biggest;
    }

    public void shiftDown(int father) {
        while (true) {
            int lchild = father * 2;
            int rchild = father * 2 + 1;
            int newFather = father;//這裏賦不賦值無所謂,如果把下面這個return改成break,那就必須賦值了

            if (lchild > size) {//如果沒有左、右孩子
                return;
            } else if (rchild > size) {//如果沒有右孩子
                newFather = max(father, lchild);
            } else {//如果有左、右孩子
                newFather = max(father, lchild, rchild);
            }

            if (newFather == father) {//如果原父結點就是三者最大,則不用繼續整理堆了
                return;
            } else {//父節點不是最大,則把大的孩子交換上來,然後繼續往下堆調整,直到滿足大根堆為止
                swap(newFather, father);
                father = newFather;//相當於繼續shiftDown(newFather)。假如newFather原來是father的左孩子,那就相當於shiftDown(2*father)
            }
        }
    }

    public static <T extends Comparable<? super T>> void sort(T[] arr) {
        int len = arr.length;
        MaxHeap<T> maxHeap = new MaxHeap<>(arr);
        maxHeap.printAsTree();
        for (int i = len - 1; i >= 0; i--) {
            arr[i] = maxHeap.popMax();
        }
    }

    public static void printArr(Object[] arr) {
        for (Object o : arr) {
            System.out.print(o);
            System.out.print("\t");
        }
        System.out.println();
    }

    public void printSpace(int n) {//打印n個空格(在這裏用‘\t’來代替)
        for (int i = 0; i < n; i++) {
            System.out.printf("%3s", "");
        }
    }

    public void printAsTree() {
        int lineNum = 1;//首先遍歷第一行
        int lines = (int) (Math.log(size) / Math.log(2)) + 1;//lines是堆的層數
        int spaceNum = (int) (Math.pow(2, lines) - 1);
        for (int i = 1; i <= size; ) { //因為在[1...size]左閉右閉區間存數據,data[0]不存數據
            
            //每層都是打印這個區間[2^(層數-1) ... (2^層數)-1]。如果堆裏的數不夠(2^層數)-1個,那就打印到size。所以取min((2^層數)-1,size).
            for (int j = (int) Math.pow(2, lineNum - 1); j <= Math.min(size, (int) Math.pow(2, lineNum) - 1); j++) {
                printSpace(spaceNum); //打印spaceNum個空格
                System.out.printf("%3s", data[j]);//打印數據
                System.out.printf("%3s", "");//圖片中綠色方框
                printSpace(spaceNum);//打印spaceNum個空格
                i++;//每打印一個元素就 + 1
            }
            lineNum++;
            spaceNum = spaceNum / 2;
            System.out.println();
        }
    }

    public static void main(String args[]) {
        Integer[] arr = {3, 5, 1, 7, 2, 9, 8, 0, 4, 6, 1, 3, 6, 1, 1};
        sort(arr);
    }
}

  執行結果:

技術分享圖片

打印二叉堆(Java實現)