Postgraduate data structure-MaxHeap

principle

Here we are building the largest heap, which is represented by a complete binary tree;
1. The top of the heap is larger than any element in the two subtrees;
2. Each subtree also meets this condition;
that is, the root is the maximum value in the tree, The root of each subtree is the maximum value in the subtree,
so we must start with the smallest subtree when constructing, so that we can construct a larger subtree

/*
*   建立大顶堆,a[1]为最大元素 
*/
typedef struct {
    /*自底向上调整每一个元素,每次构造一个子结构*/ 
    void buildMaxHeap(int a[], int len) {
        for (int i = len / 2; i >= 1;--i)
            AjustDown(a, i, len);
    }
    /*将第k个元素向下调整*/ 
    void AjustDown(int a[], int k, int len) {
        int temp = a[k];
        for (int i = 2*k;i <= len;i *= 2) {
            if (i < len && a[i] < a[i+1]) ++i;
            if (temp >= a[i]) break;
            a[k] = a[i];
            k = i;
        }
        a[k] = temp;
    }
    /*把第k个元素向上调整*/
    void AjustUp(int a[], int k) {
        int temp = a[k];
        int i = k / 2;
        while(i >= 1 && a[i] < temp) {
            a[k] = a[i];
            k = i;
            i /= 2;
        }
        a[k] = temp;
    }
    /*插入元素*/
    void InsertElement(int a[], int& len, int value) {
        a[++len] = value;
        AjustUp(a, len);
    }
    /*删除第k个元素*/
    int DeleteElement(int a[], int& len, int k) {
        int temp = a[k];
        a[len] = a[k];
        AjustDown(a, k, --len);
        return temp;
    }
}MaxHeap;

Guess you like

Origin blog.csdn.net/KIJamesQi/article/details/75903217