最小堆MinHeap源码
MinHeap.h源码
#pragma once
#include "stdafx.h"
#include <vector>
using namespace std;
class MinHeapNode
{
private:
int _nodeIndex;
float _nodeValue;
public:
MinHeapNode(float nodeValue)
{
this->_nodeIndex = 0;
this->_nodeValue = nodeValue;
}
float GetNodeValue(){return _nodeValue;}
void SetNodeValue(float nodeValue){_nodeValue = nodeValue;}
int GetNodeIndex(){return _nodeIndex;}
void SetNodeIndex(int nodeIndex){_nodeIndex = nodeIndex;}
};
class MinHeap
{
private:
vector<MinHeapNode*> _nodeList;
public:
void Up(int i);
void Down(int i);
void Add(MinHeapNode* node);
MinHeapNode* GetMin();
void RemoveMin();
};
MinHeap.cpp源码
#pragma once
#include "stdafx.h"
#include "MinHeap.h"
#include <vector>
using namespace std;
void MinHeap::Up(int i)
{
MinHeapNode* upNode = _nodeList[i];
int child = i;
while(child >0)
{
int parent = (child-1)/2;
if(upNode->GetNodeValue() >= _nodeList[parent]->GetNodeValue())
{
break;
}
_nodeList[child] = _nodeList[parent];
_nodeList[child]->SetNodeIndex(child);
child = parent;
}
_nodeList[child] = upNode;
_nodeList[child]->SetNodeIndex(child);
}
void MinHeap::Down(int i)
{
MinHeapNode* downNode = _nodeList[i];
int parent = i;
while(parent*2+1 < _nodeList.size())
{
int left = parent*2+1;
int right = parent*2+2;
int minIndex = left;
if(right < _nodeList.size())
{
if(_nodeList[right]->GetNodeValue() < _nodeList[left]->GetNodeValue())
{
minIndex = right;
}
}
if(downNode->GetNodeValue() <= _nodeList[minIndex]->GetNodeValue())
{
break;
}
_nodeList[parent] = _nodeList[minIndex];
_nodeList[parent]->SetNodeIndex(parent);
parent = minIndex;
}
_nodeList[parent] = downNode;
_nodeList[parent]->SetNodeIndex(parent);
}
void MinHeap::Add(MinHeapNode* node)
{
_nodeList.push_back(node);
node->SetNodeIndex(_nodeList.size()-1);
Up(_nodeList.size()-1);
}
MinHeapNode* MinHeap::GetMin()
{
return _nodeList.size()>0?_nodeList[0]:NULL;
}
void MinHeap::RemoveMin()
{
if(_nodeList.size()>0)
{
MinHeapNode* node = _nodeList[_nodeList.size()-1];
_nodeList.pop_back();
if(_nodeList.size()>0)
{
_nodeList[0] = node;
_nodeList[0]->SetNodeIndex(0);
Down(0);
}
}
}
MinHeapTest.h源码
#pragma once
#include "stdafx.h"
#include "MinHeap.h"
#include <iostream>
using namespace std;
class MinHeapTest
{
public:
void DoTest()
{
MinHeap* minHeap = new MinHeap();
vector<MinHeapNode*> nodelist;
nodelist.push_back(new MinHeapNode(4));
nodelist.push_back(new MinHeapNode(5));
nodelist.push_back(new MinHeapNode(8));
nodelist.push_back(new MinHeapNode(1));
nodelist.push_back(new MinHeapNode(10));
nodelist.push_back(new MinHeapNode(6));
nodelist.push_back(new MinHeapNode(3));
nodelist.push_back(new MinHeapNode(7));
nodelist.push_back(new MinHeapNode(2));
nodelist.push_back(new MinHeapNode(9));
for(int i=0;i<nodelist.size(); i++)
{
minHeap->Add(nodelist[i]);
}
while(minHeap->GetMin()!=NULL)
{
cout<<minHeap->GetMin()->GetNodeValue() << " ";
minHeap->RemoveMin();
}
cout<<endl;
}
};