вторник, 21 июня 2011 г.

Data structures: Priority Queue (based on Binary Heap)

#ifndef PRIORITY_QUEUE 
#define PRIORITY_QUEUE 

template<typename ItemType>

struct binary_heap
{
    public: 

        ItemType *heap; 
        int index; 
    
        binary_heap(int heap_size)
        {
            index=0;
            heap=new ItemType[heap_size];         
        };

        void add_item(ItemType new_item)
        {
            index++;

            heap[index]=new_item; 
            bubble_up(index);
        }; 

        ItemType get_min()
        {
            ItemType min=heap[1];
            heap[1]=heap[index];
            
            index=index-1; 
            
            bubble_down(1);
            
            return min; 
        };

    private: 
    
        void bubble_up(int n)
        {
            if (get_parent(n)!=-1)
            {
                if (heap[n]<heap[get_parent(n)]) 
                {
                    ItemType tmp=heap[n]; 
                    heap[n]=heap[get_parent(n)];
                    heap[get_parent(n)]=tmp; 
                
                    bubble_up(get_parent(n));
                }; 
            };
        }; 

        void bubble_down(int n)
        {
                int first_child=get_first_child(n); 
                
                int min_child_index=n; 

                for (int i=0; i<=1; i++)
                {
                    if ((first_child+i)<=index) 
                    {
                        if (heap[min_child_index]>heap[first_child+i]) min_child_index=first_child+i; 
                    }; 
                };

                if (min_child_index!=n)
                {
                    ItemType tmp=heap[min_child_index]; 
                    heap[min_child_index]=heap[n];
                    heap[n]=tmp; 

                    bubble_down(min_child_index);
                };
        };

        int get_parent(int n)
        {
            if (n==1) return -1; 

            return (int)(n/2); 
        }; 

        int get_first_child(int n)
        {
                return (n*2); 
        }; 
};

template <typename ItemType> 

struct priority_queue
{
    public:
        
        binary_heap<ItemType> *pq; 
        int ITEMS_COUNT; 
     
        priority_queue(int items_num)
        {
            pq=new binary_heap<ItemType>(items_num);         
            ITEMS_COUNT=pq->index;
        };

        void push(ItemType new_item)
        {
            pq->add_item(new_item); 
        };

        ItemType pop()
        {
            return pq->get_min();
        };
};

Комментариев нет:

Отправить комментарий

Санкт-Петербург, июль 2021

Фактически был один день, поэтому публикую все так как есть, по порядку. Типичные виды Невы не выкладываю - приелось уже.  1. На следующий д...