最大堆的一些基本操做

若是一棵徹底二叉樹的任意一個非終結點的元素都不小於其子結點,則此二叉樹稱爲最大堆。數組

如下是最大堆的定義和一些基本操做(最小堆與之相似):code

//堆的定義
typedef struct{
    int elements[Maxsize];
    int n;
}HEAP;

因爲堆屬於徹底二叉樹,所以能夠方便的直接使用數組來表示。將堆的結點從根開始,自左而右,自上而下地進行編號,按照其順尋保存在一個覺得數組中便可,n爲堆的結點數量。element

//建立一個空堆
void MaxHeap(HEAP heap)
{
    heap.n=0;
}

//判斷堆是否爲空
bool HeapEmpty(HEAP heap)
{
    if(heap.n == 0)
        return true;
    else 
        return false;
}

//判斷堆是否爲空
bool HeapFull(HEAP heap)
{
    return (heap.n==Maxsize-1);
}

在最大堆中插入數據時,須要在其數組最後添加數據,爲了保持最大堆的性質,還須要將該數據與其父結點進行比較,若是大於父結點的值,則將其與父結點交換,並繼續向上比較,直到該數據不大於其父結點或到達根結點爲止。ast

//插入數據
void Insert(HEAP heap, int element)
{
    int i;
    if(!HeapFull(heap))
    {
        i=heap.n+1;
        while((i!=1) && (element>heap.elements[i/2]))
        {
            heap.elements[i] = heap.elements[i/2];
            i/=2;
        }
        heap.elements[i]=element;
    }
    else
    {
        cout<<"該堆已滿!"<<endl;
    }
}

刪除堆中的最大元素時必定是刪除堆的根結點。爲了保持其性質,咱們將最後一個結點一直根結點中,而後比較結點i與其較大子結點的元素,若是小於較大子結點的元素,則進行交換,並令這個子結點成爲新的結點i繼續向下比較。二叉樹

void DeleteMax(HEAP &heap)
{
    int parent = 1, child = 2;
    if(!HeapEmpty(heap))
    {
        int last = heap.n - 1; 
        heap.elements[1]=heap.elements[last];
        while(child < heap.n)
        {
            if(heap.elements[child] < heap.elements[child+1])
                child++;
            if(heap.elements[parent] < heap.elements[child])
            {
                int temp = heap.elements[parent];
                heap.elements[parent]=heap.elements[child];
                heap.elements[child]=temp;
            }
            parent = child;
            child *= 2;
        }
    }
    else
        cout<<"該堆爲空!"<<endl;
}

查找元素是否在堆中:數據

//查找某個元素是否在堆中,若在則返回其位置,不在則返回0
int Find(HEAP heap, int e, int start)
{
    int n = start;
    while(n < heap.n)
    {
        if(heap.elements[n] == e)
            return n;
        else
        {
            if(heap.elements[2*n] < e)
                n = 2*n + 1;
            else if (heap.elements[2*n] != e)
                n++;
            else if(heap.elements[2*n] == e)
                return 2*n;
        }
    }
    return 0;
}
相關文章
相關標籤/搜索