数据结构学习笔记(三) 树形结构之筛选法建立最小堆

以下是使用筛选法建立最小堆的代码,用于建堆的数据为{35,26,48,10,59,64,17,23,45,31}。
筛选法也即,从堆的最右下一个分支节点起,自下而上遍历每一个分支节点,使得以该分支节点为根的子树成为最小堆。

//筛选法+建立最小堆
#include
using namespace std;

//类型定义与变量说明
const int DefaultSize=100;
typedef int datatype;
typedef struct
{
    datatype key;//关键字
    //......其他属性字段
}node;
typedef struct
{
    node *Heap;
    int CurrentSize;
    int MaxHeapSize;
}minHeap;
minHeap mh;
int start,EndOfHeap;

//筛选法
void FilterDown(minHeap &mh,int start,int EndOfHeap)
{
    int i=start,j=2*i+1;
    node temp=mh.Heap[i];
    while(j<=EndOfHeap)
    {
        if(jmh.Heap[j+1].key)
            j++;
        if(temp.key<=mh.Heap[j].key)
            break;
        else
        {
            mh.Heap[i]=mh.Heap[j];
            i=j;
            j=2*j+1;
        }
        mh.Heap[i]=temp;
    }
}

//建立最小堆
void MinHeap(minHeap &mh,node A[],int n)
{
    int i,CurrentPos;
    mh.MaxHeapSize=DefaultSizenew node[mh.MaxHeapSize];
    if(mh.Heap==NULL)
    {
        cout<<"Memory Allocation Error1"<return;
    }
    for(i=0;i2)/2;
    while(CurrentPos>=0)
    {
        FilterDown(mh,CurrentPos,mh.CurrentSize-1);
        CurrentPos--;
    }
}

//测试方法
int main()
{
    node A[10]={35,26,48,10,59,64,17,23,45,31};
    MinHeap(mh,A,10);
    for(int i=0;i<10;i++)
        cout<" ";
    cout<return 0;
}

你可能感兴趣的:(数据结构学习笔记)