I am looking for a general purpose priority queue in R
. Does R has any general purpose priority queue implementation (package) like Java PriorityQueue
class or Python heapq
?
I went ahead and implemented a basic queue as an R Reference Class. The details can be found here. It's been extended to handle a priority queue, as documented here.
The basic and priority queue implementations are now available as the liqueueR package on CRAN, with a development version on GitHub.
You can use the following implementation from Rosetta Code, but beware that insertion takes O(n log n)
PriorityQueue <- function() {
keys <<- values <<- NULL
insert <- function(key, value) {
temp <- c(keys, key)
ord <- order(temp)
keys <<- temp[ord]
values <<- c(values, list(value))[ord]
}
pop <- function() {
head <- values[[1]]
values <<- values[-1]
keys <<- keys[-1]
return(head)
}
empty <- function() length(keys) == 0
list(insert = insert, pop = pop, empty = empty)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With