Class Ferret::Utils::PriorityQueue
In: ext/r_utils.c
Parent: Object

Summary

A PriorityQueue is a very useful data structure and one that needs a fast implementation. Hence this priority queue is implemented in C. It is pretty easy to use; basically you just insert elements into the queue and pop them off.

The elements are sorted with the lowest valued elements on the top of the heap, ie the first to be popped off. Elements are ordered using the less_than ’<’ method. To change the order of the queue you can either reimplement the ’<’ method pass a block when you initialize the queue.

You can also set the capacity of the PriorityQueue. Once you hit the capacity, the lowest values elements are automatically popped of the top of the queue as more elements are added.

Example

Here is a toy example that sorts strings by their length and has a capacity of 5;

  q = PriorityQueue.new(5) {|a, b| a.size < b.size}
  q << "x"
  q << "xxxxx"
  q << "xxx"
  q << "xxxx"
  q << "xxxxxx"
  q << "xx" # hit capacity so "x" will be popped off the top

  puts q.size     #=> 5
  word = q.pop    #=> "xx"
  q.top << "yyyy" # "xxxyyyy" will still be at the top of the queue
  q.adjust        # move "xxxyyyy" to its correct location in queue
  word = q.pop    #=> "xxxx"
  word = q.pop    #=> "xxxxx"
  word = q.pop    #=> "xxxxxx"
  word = q.pop    #=> "xxxyyyy"
  word = q.pop    #=> nil

Methods

<<   adjust   capacity   clear   clone   insert   new   pop   size   top  

Public Class methods

Returns a new empty priority queue object with an optional capacity. Once the capacity is filled, the lowest valued elements will be automatically popped off the top of the queue as more elements are inserted into the queue.

Public Instance methods

Insert an element into a queue. It will be inserted into the correct position in the queue according to its priority.

Sometimes you modify the top element in the priority queue so that its priority changes. When you do this you need to reorder the queue and you do this by calling the adjust method.

Returns the capacity of the queue, ie. the number of elements that can be stored in a Priority queue before they start to drop off the end. The size of a PriorityQueue can never be greater than its capacity

Clears all elements from the priority queue. The size will be reset to 0.

Returns a shallow clone of the priority queue. That is only the priority queue is cloned, its contents are not cloned.

Insert an element into a queue. It will be inserted into the correct position in the queue according to its priority.

Returns the top element in the queue removing it from the queue.

Returns the size of the queue, ie. the number of elements currently stored in the queue. The size of a PriorityQueue can never be greater than its capacity

Returns the top element in the queue but does not remove it from the queue.

[Validate]