Small roots heap (Heap) detailed implementation

Introduction heap

Heap is a data structure having the following features:

1) complete binary tree
2) value stored in the heap is a partial order

Value the value of the parent node of the child node is equal to or less than: Min-heap

Value the value of the parent node of the child node is greater than or equal to: Max-heap

figure 1

Heap memory

Generally used to represent the parent node array subscript stack, i is the node on the (i-1) / 2. Left and right child node of its subscript 2 * i + 1 and 2 * i + 2, respectively. The left and right child nodes 0 node subscripts 1 and 2 respectively.

figure 2

Since the stack stored in the next standard counting from 0 in the array, therefore, to set the stack is labeled node i:

(1) if i = 0, i is the root node, no parent node; otherwise, the parent of node i to node node (i-1) / 2;

(2) If 2i + 1> n-1, then no left child node i; otherwise, the left child node i to node 2i + 1;

(3) If 2i + 2> n-1, i is not the right child node; otherwise the right child node i to node 2i + 2.

Stack operations: insert elements stack rootlets

Insert an element: a new element is added to the end of the heap, and then update the tree in order to restore order in the stack.
Each time you insert the new data on the array are final. It is found from the parent of the new data to the root node is necessarily an ordered sequence, the task now is to insert the new data to the order data - This is analogous to sorting in the data directly into a incorporated into the ordered interval. We need, compared with the key from the parent node of the Internet, swap.

image 3

Heap Action: Remove piles of small root smallest element

By definition, every pile of 0 to delete data. In order to facilitate reconstruction of the stack, the operation is the actual value of the last data assigned to the root node, the number of elements in the stack -1, then beginning of a correction downward from the root node from. First adjustment in the left and right son node to find the minimum, if the parent node than this minimum small child nodes further indicates not adjusted, whereas the parent node and then switching it back of the considered node. Equivalent from the root to "sink" a data process.

Figure 4

Heap: Create a heap

For the leaf nodes, not the order of adjustment, according to the nature of the full binary tree, the leaf nodes larger than 1. Therefore, the number of internal nodes i = n / 2 -1, n goes from the start. The last is from a leaf node node start.

Heapsort

Heap after the first 0 if the data in ascending order, create piles built is the largest heap of data. This extracted data, on the last element of the array, the current number of elements -1, and then perform the removal of the stack. In this way the stack of data 0 is the maximum heap data, repeating the above steps until only one data heap array element has been ordered.

Small root heap implementation

#include <iostream>
using namespace std;

const int DefaultSize = 50;

template<typename T>
class MinHeap
{
public:
    //构造函数:建立空堆
    MinHeap(int sz=DefaultSize)
    {
        maxHeapSize = (DefaultSize < sz) ? sz : DefaultSize;
        heap = new T[maxHeapSize];
        currentSize = 0;
    }

    //构造函数通过一个数组建立堆
    MinHeap(T arr[],int n)
    {
        maxHeapSize = (DefaultSize < n) ? n : DefaultSize;
        heap = new T[maxHeapSize];
        for(int i=0;i<n;i++)
        {
            heap[i] = arr[i];
        }
        currentSize = n;
        int currentPos = (currentSize - 2) / 2; //找最初调整位置:最后分支结点
        while (currentPos>=0)   //自底向上逐步扩大形成堆
        {
            siftDowm(currentPos, currentSize - 1);  //局部自上向下下滑调整
            currentPos--;   //再向前换一个分支结点
        }
    }

    //将x插入到最小堆中
    bool Insert(const T& x)
    {
        if(currentSize==maxHeapSize)
        {
            cout << "Heap Full!" << endl;
            return false;
        }
        heap[currentSize] = x;  //插入
        siftUp(currentSize);    //向上调整
        currentSize++;  //堆计数+1
        return true;
    }

    bool RemoveMin(T& x)
    {
        if(!currentSize)
        {
            cout << "Heap Empty!" << endl;
            return false;
        }
        x = heap[0];    //返回最小元素
        heap[0] = heap[currentSize - 1];    //最后元素填补到根结点
        currentSize--;
        siftDowm(0, currentSize - 1);   //自上向下调整为堆
        return true;
    }

    void output()
    {
        for(int i=0;i<currentSize;i++)
        {
            cout << heap[i] << " ";
        }
        cout << endl;
    }

protected:

    //最小堆的下滑调整算法
    void siftDowm(int start, int end)   //从start到end下滑调整成为最小堆
    {
        int cur = start;
        int min_child = 2 * cur + 1;    //先记max_child是cur的左子女位置
        T temp = heap[cur];
        while (min_child <=end)
        {
            if (min_child<end&&heap[min_child]>heap[min_child + 1]) //找到左右孩子中最小的一个
                min_child++;

            if(temp<=heap[min_child])
                break;
            else
            {
                heap[cur] = heap[min_child];
                cur = min_child;
                min_child = 2 * min_child + 1;
            }
        }
        heap[cur] = temp;
    }

    //最小堆的上滑调整算法
    void siftUp(int start)  //从start到0上滑调整成为最小堆
    {
        int cur = start;
        int parent = (cur - 1) / 2;
        T temp = heap[cur];
        while (cur>0)
        {
            if(heap[parent]<=temp)
                break;
            else
            {
                heap[cur] = heap[parent];
                cur = parent;
                parent = (parent - 1) / 2;
            }
        }
        heap[cur] = temp;   //回放temp中暂存的元素
    }
private:    //存放最小堆中元素的数组
    T* heap;
    int currentSize;    //最小堆中当前元素个数
    int maxHeapSize;    //最小堆最多允许元素个数
};

//------------------------主函数-------------------------
int main(int argc, char* argv[])
{
    MinHeap<int> h;
    h.Insert(8);
    h.Insert(5);
    h.Insert(7);
    h.Insert(9);
    h.Insert(6);
    h.Insert(12);
    h.Insert(15);
    h.output();

    int out;
    cout << static_cast<int> (h.RemoveMin(out)) << endl;
    h.output();

    int arr[10] = { 15,19,13,12,18,14,10,17,20,11 };
    MinHeap<int> h1(arr,10);
    h1.output();
}

Guess you like

Origin www.cnblogs.com/WindSun/p/11444446.html