Search code examples
rustpriority-queue

Reverse order Priority Queue


Does anyone know if it is possible to reverse the order in a priority queue in Rust? When I peek the queue, I want the lowest i32 to be received. However, it seems that it by default returns the highest i32.

Edit

This is the package I am using: docs.rs/priority-queue/1.2.0/priority_queue


Solution

  • As per the documentation of the crate (package).

    I believe you should be using DoublePriorityQueue instead of PriorityQueue as it offers to peek in the queue the highest value or the lowest. Using peek_max or peek_min respectively.

    See the snippet of code they provide in the documentation:

    use priority_queue::DoublePriorityQueue;
    
    let mut pq = DoublePriorityQueue::new();
    
    assert!(pq.is_empty());
    pq.push("Apples", 5);
    pq.push("Bananas", 8);
    pq.push("Strawberries", 23);
    
    assert_eq!(pq.peek_max(), Some((&"Strawberries", &23)));
    assert_eq!(pq.peek_min(), Some((&"Apples", &5)));
    
    pq.change_priority("Bananas", 25);
    assert_eq!(pq.peek_max(), Some((&"Bananas", &25)));
    
    for (item, _) in pq.into_sorted_iter() {
        println!("{}", item);
    }