Skip to content

Instantly share code, notes, and snippets.

@marcinwyszynski
Created January 12, 2012 12:50
Show Gist options
  • Save marcinwyszynski/1600321 to your computer and use it in GitHub Desktop.
Save marcinwyszynski/1600321 to your computer and use it in GitHub Desktop.
A simple PriorityQueue in Ruby
class PriorityQueue
def initialize() @store = {} end
# Takes element and it's priority.
# Returns an array of elements with the same priority.
def enq(el, p)
@store[p] ? @store[p].push(el) : @store[p] = [el]
return @store[p]
end
# Returns the element/priority combination of the
# element with the highest priority from the queue
def deq
key = @store.keys.sort.last
el = @store[key].shift
@store.delete(key) if @store[key].empty?
return [el, key]
rescue NoMethodError
nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment