Implementation of Priority Queue ADT

Priority queue is a special queue, based on a binary heap implementation, has good algorithm performance in inserting and deleting elements. Since the height of the binary heap is logN, it is adjusted at most logN times when inserting or deleting elements, and the time complexity is O(logN).
Give the priority queue ADT code, which priority_judgeis the priority judgment. Generally speaking, when inserting and deleting operations, the higher priority should be adjusted to the top of the heap, and the lower priority should be adjusted to the bottom of the heap. When adjusting elements, in order to eliminate the influence of constants, first back up the target element to be adjusted, and then compare the elements to be adjusted with the element in turn. Specifically, when inserting elements, we use the idea of ​​filtering, so in During the adjustment process, the priority of the child node and the parent node are compared from the bottom of the heap. If the priority of the child node is high, the parent node needs to be moved down, which is equivalent to filtering on the target element to be adjusted; similarly, when deleting elements , We adopt the idea of ​​sinking, comparing the priority of the parent node and the two child nodes from the top of the heap . If the priority of the child node is higher than the parent node, the child node needs to be moved up, which is equivalent to adjustment The target element sinks. Finally, save the element in the corresponding position and complete an adjustment.

template<class T>
class Priority_Queue//优先队列ADT
{
    
    
private:
    T t[maxSize];
    int len;//优先队列的长度
public:
    void Init();//初始化
    T Top();//返回优先级最大的元素
    void Pop();//弹出优先级最大的元素,同时调整堆
    void Push(T x);//插入元素,同时调整堆
    int Size();//返回队列中元素的个数
    bool Empty();//队列是否为空
};
template<class T>
void Priority_Queue::Init()
{
    
    
    len=0;
}
template<class T>
T Priority_Queue::Top()
{
    
    
    return t[1];
}
template<class T>
int Priority_Queue::Size()
{
    
    
    return len;
}
template<class T>
void Priority_Queue::Pop()//利用下沉的思想
{
    
    
    T t1=t[len];
    len--;
    int l,i=1;
    for(i=1;2*i<=len;i=l)
    {
    
    
        l=2*i;//子节点
        if(l<len&&priority_judge)l++;
        if(priority_judge)t[i]=t[l];
        else break;
    }
    t[i]=t1;
}
template<class T>
void Priority_Queue::Push(T x)//利用上滤的思想
{
    
    
    int i;
    len++;
    i=len;
    for(;i>=2;i=i/2)
    {
    
    
        if(priority_judge)t[i]=t[i/2];
        else break;
    }
    t[i]=x;
}
template<class T>
bool Priority_Queue::Empty()
{
    
    
    return len==0?true:false;
}

Guess you like

Origin blog.csdn.net/upc122/article/details/106223662