您的位置:首页 > 其它

优先队列

2016-03-17 19:17 225 查看
算法导论:优先队列的实现,只实现了基本的功能,并不完善

#ifndef _PRIORITY_QUEUE_H_
#define _PRIORITY_QUEUE_H_

#include<vector>
#include<limits>

class PriorityQueue
{
public:
PriorityQueue();
PriorityQueue(std::vector<int>A);
std::vector<int> heapsort(); //堆排序
int heap_maxmum(); //返回最大元素
int heap_extract_max(); //删除最大元素,并返回最大元素
void heap_increase_key(int i, int key); //修改位置i的元素的值
void max_heap_insert(int key); //插入元素
std::vector<int> getA();
private:
std::vector<int>m_A;
int m_heap_size;
void max_heapify(std::vector<int>&A,int beginIndex,int heap_size);
void build_max_heap(std::vector<int>&A,int heap_size);
};
#endif

#include "PriorityQueue.h"

PriorityQueue::PriorityQueue()
{

}

PriorityQueue::PriorityQueue(std::vector<int>A)
{
m_heap_size = A.size();
m_A = A;
build_max_heap(m_A,m_heap_size);
}

void PriorityQueue::max_heapify(std::vector<int>&A,int beginIndex,int heap_size)
{
int l = 2 * beginIndex;
int r = 2 * beginIndex + 1;
int largest = -1;
if (l <= heap_size && A[l - 1] > A[beginIndex - 1])
{
largest = l;
}
else
{
largest = beginIndex;
}
if (r <= heap_size && A[r - 1] > A[largest - 1])
{
largest = r;
}
if (largest != beginIndex)
{
std::swap(A[beginIndex - 1], A[largest - 1]);
max_heapify(A,largest,heap_size);
}
}

void PriorityQueue::build_max_heap(std::vector<int>&A,int heap_size)
{

for (int i = heap_size / 2; i >= 1; --i)
{
max_heapify(A,i,heap_size);
}
}

std::vector<int> PriorityQueue::heapsort()
{
std::vector<int> A = m_A;
int heap_size = m_heap_size;
build_max_heap(A,heap_size);
for (int i = heap_size - 1; i >= 1; --i)
{
heap_size = heap_size - 1;
std::swap(A[0], A[i]);
max_heapify(A,1,heap_size);
}
return A;
}

int PriorityQueue::heap_maxmum()
{
if (m_heap_size > 0)
return m_A[0];
else
return std::numeric_limits<int>::min();
}

int PriorityQueue::heap_extract_max()
{
int max = std::numeric_limits<int>::min();
if (m_heap_size > 0)
{
max = m_A[0];
std::swap(m_A[0], m_A[m_heap_size - 1]);
m_heap_size = m_heap_size - 1;
max_heapify(m_A,1, m_heap_size);
}
return max;
}

void PriorityQueue::heap_increase_key(int i, int key)
{
if (key >= m_A[i-1])
{
m_A[i-1] = key;
while (i > 1 && m_A[int(i/2)-1] < m_A[i-1])
{
std::swap(m_A[i-1], m_A[int(i/2)-1]);
i = i/2;
}
}

}

void PriorityQueue::max_heap_insert(int key)
{
m_heap_size = m_heap_size + 1;
if (m_A.size() == (m_heap_size-1))
{
m_A.push_back(std::numeric_limits<int>::min());
}
else
{
m_A[m_heap_size - 1] = std::numeric_limits<int>::min();
}
heap_increase_key(m_heap_size, key);
}

std::vector<int> PriorityQueue::getA()
{
return m_A;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法导论