How do I implement a heap in Rust?

CK CK 3788 
Created at
Updated at  
686 0 0

To implement a heap in Rust, you can use a binary heap for an efficient priority queue. Rust provides a standard library implementation with the BinaryHeap type, but you can also create a custom heap structure if you need more control.

How do I implement a heap in Rust?

Using std::collections::BinaryHeap

The simplest way is to use the BinaryHeap from the standard library:

use std::collections::BinaryHeap;

fn main() {
    // Create a new BinaryHeap
    let mut heap = BinaryHeap::new();

    // Push elements onto the heap
    heap.push(4);
    heap.push(1);
    heap.push(7);
    heap.push(3);

    // Pop elements off the heap in descending order
    while let Some(value) = heap.pop() {
        println!("{}", value);
    }
}

Key Points:

  • The BinaryHeap stores elements in a max-heap order (largest element at the top).
  • For a min-heap, you can store elements as negative values or use a custom type with Ord implementation.

Custom Heap Implementation

If you want to implement your own heap for learning or specific requirements, here's an example:

 

Min-Heap Implementation

pub struct Heap<T> {
    elements: Vec<T>,
}

impl<T: Ord> Heap<T> {
    // Create a new empty heap
    pub fn new() -> Self {
        Heap {
            elements: Vec::new(),
        }
    }

    // Insert an element into the heap
    pub fn push(&mut self, value: T) {
        self.elements.push(value);
        self.bubble_up(self.elements.len() - 1);
    }

    // Remove and return the smallest element
    pub fn pop(&mut self) -> Option<T> {
        if self.elements.is_empty() {
            return None;
        }
        let result = self.elements.swap_remove(0);
        if !self.elements.is_empty() {
            self.bubble_down(0);
        }
        Some(result)
    }

    // Peek at the smallest element without removing it
    pub fn peek(&self) -> Option<&T> {
        self.elements.get(0)
    }

    fn bubble_up(&mut self, mut index: usize) {
        while index > 0 {
            let parent = (index - 1) / 2;
            if self.elements[index] >= self.elements[parent] {
                break;
            }
            self.elements.swap(index, parent);
            index = parent;
        }
    }

    fn bubble_down(&mut self, mut index: usize) {
        let len = self.elements.len();
        loop {
            let left = 2 * index + 1;
            let right = 2 * index + 2;

            let mut smallest = index;

            if left < len && self.elements[left] < self.elements[smallest] {
                smallest = left;
            }
            if right < len && self.elements[right] < self.elements[smallest] {
                smallest = right;
            }
            if smallest == index {
                break;
            }
            self.elements.swap(index, smallest);
            index = smallest;
        }
    }
}

fn main() {
    let mut heap = Heap::new();

    // Insert elements
    heap.push(4);
    heap.push(1);
    heap.push(7);
    heap.push(3);

    // Peek at the smallest element
    println!("Smallest: {:?}", heap.peek());

    // Pop elements in ascending order
    while let Some(value) = heap.pop() {
        println!("{}", value);
    }
}

Explanation:

  1. Structure: The Heap struct uses a Vec to store elements.
  2. Operations:
    • push: Adds an element and reorders the heap by "bubbling up."
    • pop: Removes the smallest element and reorders by "bubbling down."
    • peek: Returns the smallest element without removing it.
  3. Bubble Up: Ensures the heap property is maintained after adding an element.
  4. Bubble Down: Ensures the heap property after removing the root element.

This implementation creates a min-heap. You can adjust it to create a max-heap by reversing the comparison logic (< to >). This custom heap is more educational and flexible for specific scenarios.

Tags BinaryHeap Heap Rust BinaryHeap Rust Heap Facebook X
Comments 0
Similar posts
  1. Rust Std library types
    370
  1. How do I implement a stack in Rust?
    771
  2. Rust-GPU-tools for interacting with various GPU APIs
    757
  3. Rust array is fixed size. Can I modify its content?
    587
  4. Rust Example for Array and Dyamic Element Management (aka Vector-based Element Management)
    625
  5. The || syntax in Rust - also known as a closure
    602
  6. Basic Rust Thread Example to Perform Concurrent Computation
    619
  7. Multi-threaded HLS Server in Rust
    774
  8. Run a specific module in a external file with Rust
    571
  9. Question(?) Operator in Rust
    573
  10. Rust code example to access MySQL
    1,100
  11. Rust Documentation
    316
  12. Rust Compatibility
    726
  13. Rust Unsafe Operations
    369
  14. Rust Testing
    1,246
  15. Rust Std misc
    375
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    31
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    57
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    51
  4. How do I create animated background for Google Meet?
    23,256
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    273
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    105
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    170
  8. Array of arguments passed to script in PHP
    99
  9. Invalid Auction Storms in Ad Tech
    108
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    209
  11. The Two Clocks of Ad Server Architecture
    78
  12. Frequency Cap Architecture Overview
    527
  13. Collecting Proof-of-Play from 100,000 Screens
    154
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    304
  15. What is RedisVL?
    117
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    247
  17. TPU & GPU Cluster Management Tools
    258
  18. The Concept of Scaffolding in AI Agents
    245
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    599
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    269
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    355
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    207
  23. Machine Learning: Training vs. Ranking
    231
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    229
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    204
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    264
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    674
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    201
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    233