🐻
berkeley
  • #Despair
  • 16A/B
    • Thevenin and Norton Equivalence
    • Resistive Touchscreen
    • Trilateration and Correlation
    • RC Circuits & Transient Analysis
  • 61B
    • Testing
    • References in Java
    • Linked Lists in Java
    • Implementation Inheritance
    • Comparables and Iterators
    • Casting
    • Lists and Sets
    • Asymptotics
    • Trees
    • Hashing
    • PriorityQueue and Heap
    • Graphs, Tree Traversals
    • Tries
    • Sorting
  • Discrete Mathematics
    • Sets + Mathematical Notation
    • Logic and Proofs
    • Induction
    • Cryptography/RSA
    • Modular Arithmetic
    • Discrete Probability
  • Linear Algebra
    • Linear Equations
    • Matrix Algebra
    • Determinants
    • Vector Spaces
    • Eigenvectors and Eigenvalues
    • Projections and Orthogonality
    • SVD/PCA
  • Math 275 — Ordinary Differential Equations
    • Math 275 — Overview
    • Modeling via Differential Equations
    • Linear Systems
  • INTEGBI 35AC
    • Humans Came From Fish
    • Evolution's History
    • Typology
    • The Human Diaspora
  • 170
    • Basics
    • Divide and Conquer
    • Fast Fourier Transform
    • Graphs
    • Greedy
  • 61C
    • Pointers and Memory
    • Floating Point
    • Compliation, Assembly, Linking, Loading
    • RISC-V, Assembly
Powered by GitBook
On this page
  • Priority Queues
  • Heaps
  • Insertion:
  • Deletion:
  • Representation

Was this helpful?

  1. 61B

PriorityQueue and Heap

Priority Queues

A minPQ is a collection of items where the smallest item is kept track of. You can add items to it, get the smallest item from it, and remove the smallest item from it. Priority queues in general can use a different comparison (a minPQ compares by size, holding the minimum at any point in time.)

Heaps

A binary min-heap is a binary tree where every node is less than or equal to both of its children. A tree is complete if it's missing items only at the bottom level and all nodes are as far left as possible.

Insertion:

  • Add to end of heap.

  • Swap with parents until we have a heap again.

Deletion:

  • Swap the last item of the heap into the root.

  • Sink down the hierarchy.

Representation

Because a heap is a complete tree, we can simply represent it as an array, where the index of a parent node is

public int parent(int k) {
    return (k - 1) / 2
}

Because of the way integer division works in Java, this will always work for both parents.

We can also leave one empty spot, where the location of a parent and its children is

leftChild(k) = 2k
rightChild(k) = 2k + 1
parent(k) = k/2

to make things simpler.

PreviousHashingNextGraphs, Tree Traversals

Last updated 4 years ago

Was this helpful?