Created
January 12, 2012 12:50
-
-
Save marcinwyszynski/1600321 to your computer and use it in GitHub Desktop.
A simple PriorityQueue in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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