{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"I've lost count of the number of times I have had to re-learn how binary heaps work. It's time for another refresher. Here are some notes.\n",
""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Elegant Economy\n",
"\n",
"The original binary heap representation appeared in [1964](https://en.wikipedia.org/wiki/Binary_heap). By today's standards it is elegant and economical.\n",
"\n",
"Data in a binary heap is stored in an array. New elements are inserted, initially, at the end of the array.\n",
"\n",
"The array, `A`, is a linearized binary tree. Each element in the array corresponds to a location in a fixed-structure binary tree. That is, `A[n]` always represents a specific node in the binary tree.\n",
"\n",
"The first element of `A` is always the root of the tree – the top of the heap. Assuming array indexing is 1-based, the children of tree node `A[i]` are always stored at `A[i * 2]` and `A[(i * 2) + 1]`.\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Full and Balanced\n",
"\n",
"In our current model of the electron \"shells\" of an atom, all of the inner shells are always filled to capacity with electrons. Only the outermost shell may be incompletely filled.\n",
"\n",
"Similarly, new elements are always added to the end of `A`. As a result the inner levels of the corresponding binary tree are always full. At most one leaf node is empty at any time."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Order\n",
"\n",
"The values in a binary heap are partially ordered in one of two ways.\n",
"\n",
"In a max heap, the value in any node is always ≥ the value of either of its children node. The maximum value in such a heap is always stored in the root node. (There it is again: the top of the heap.)\n",
"\n",
"In a min heap, the value in any node is always ≤ the value of either child; so the minimum value is always at the top of the heap.\n",
"\n",
"This ordering relationship could be encoded by an ordering function."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import typing as tp\n",
"import abc\n",
"import random"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"class Comparable(abc.ABC):\n",
" @abc.abstractmethod\n",
" def __ge__(self, other: tp.Any) -> bool: ...\n",
"\n",
" @abc.abstractmethod\n",
" def __lt__(self, other: tp.Any) -> bool: ...\n",
"\n",
"\n",
"ValueType = tp.TypeVar('ValueType', bound=Comparable)\n",
"OrderFn = tp.Callable[[ValueType, ValueType], bool]\n",
"ValueList = tp.List[ValueType]"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"def max_heap(v1: ValueType, v2: ValueType) -> bool:\n",
" return v1 >= v2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Insertion\n",
"\n",
"To insert a new value into a binary heap, first append the new value to the end of the heap array `A`. Then compare the new value to its parent, swapping if the two values do not satisfy the ordering function (e.g., parent ≥ child) for this heap."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"class InsertableBinaryHeap:\n",
" def __init__(self, order_fn: OrderFn) -> None:\n",
" self._ordered = order_fn\n",
" self._a: ValueList = []\n",
"\n",
" def empty(self) -> bool:\n",
" return len(self._a) <= 0\n",
"\n",
" def insert(self, new_value: ValueType) -> None:\n",
" i = len(self._a)\n",
" self._a.append(new_value)\n",
" while i > 0:\n",
" # Zero-based indexing is a bear.\n",
" # i = (i_parent + 1) * 2 - 1, so:\n",
" i_parent = (i + 1) // 2 - 1\n",
" v: ValueType = self._a[i]\n",
" v_parent: ValueType = self._a[i_parent]\n",
" if not self._ordered(v_parent, v):\n",
" self._a[i_parent], self._a[i] = v, v_parent\n",
" i = i_parent\n",
"\n",
" def array(self) -> tp.List[ValueType]:\n",
" return self._a[:]"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Empty initially: True\n",
"Empty after insertion: False\n"
]
},
{
"data": {
"text/plain": [
"[7, 6, 5, 3, 2, 1, 4, 0]"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"bh = InsertableBinaryHeap(max_heap)\n",
"print(\"Empty initially:\", bh.empty())\n",
"\n",
"for i in range(8):\n",
" bh.insert(i)\n",
"print(\"Empty after insertion:\", bh.empty())\n",
"bh.array()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Removal\n",
"\n",
"The binary heap is often used as the underlying structure for a priority queue, which supports add (aka push, insert) and remove (aka pop) operations. Removal from a priority queue always returns the top-priority item – the top of the underlying heap.\n",
"\n",
"When the root is removed, one of the remaining items needs to be moved into the root position, and the heap needs to be re-organized to maintain its ordering.\n",
"\n",
"Start by making the last array item the new heap root. (This is guaranteed to break the ordering relationship of the heap.) Then, starting from the root, compare each node to its children. If they satisfy the ordering relationship, stop. Otherwise, swap with the child which, according to the heap's ordering, should be root-most. Then continue rebalancing with the subtree whose child was swapped.\n"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"class PriorityQueue(InsertableBinaryHeap):\n",
" def remove(self) -> ValueType:\n",
" # Let Python raise exceptions if the heap is empty.\n",
" result: ValueType = self._a[0]\n",
" self._re_root()\n",
" return result\n",
"\n",
" def _re_root(self) -> None:\n",
" new_root = self._a.pop()\n",
" # If the array is now empty, then new_root was the only item -- it will\n",
" # be returned by remove(). Otherwise, there is at least one child, and\n",
" # we need to rebalance.\n",
" newlen = len(self._a)\n",
" if newlen > 0:\n",
" self._a[0] = new_root\n",
" self._rebalance()\n",
"\n",
" def _rebalance(self) -> None:\n",
" # From https://en.wikipedia.org/wiki/Binary_heap#Extract\n",
" i = 0\n",
" a = self._a\n",
"\n",
" while True:\n",
" # zero-based indexing leads to this fenceposting nonsense.\n",
" i_left = (i + 1) * 2 - 1\n",
" i_right = i_left + 1\n",
"\n",
" i_hoist = self._rvi(self._rvi(i, i_left), i_right)\n",
" if i_hoist == i:\n",
" return\n",
"\n",
" a[i], a[i_hoist] = a[i_hoist], a[i]\n",
" i = i_hoist\n",
"\n",
" def _rvi(self, i_parent: int, i_child: int) -> int:\n",
" # Given a parent \"node\" index and a child index, return the index\n",
" # whose value should be root-most, given self's ordered relationship.\n",
" a = self._a\n",
" if (i_child < len(a)) and not self._ordered(a[i_parent], a[i_child]):\n",
" return i_child\n",
" return i_parent"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Values = [19, 78, 26, 86, 78, 23, 32, 52, 98, 37, 6, 82, 94, 42, 18, 70, 91, 32, 66, 101]\n",
"Heap array: [101, 98, 94, 86, 91, 82, 42, 78, 66, 78, 6, 23, 32, 26, 18, 19, 70, 32, 52, 37]\n",
"101 98 94 91 86 82 78 78 70 66 52 42 37 32 32 26 23 19 18 6 \n"
]
}
],
"source": [
"q = PriorityQueue(max_heap)\n",
"\n",
"sep = \"Values = [\"\n",
"for i in range(20):\n",
" v = random.randint(1, 101)\n",
" print(f\"{sep}{v}\", end=\"\")\n",
" q.insert(v)\n",
" sep = \", \"\n",
"print(\"]\")\n",
"\n",
"print(\"Heap array:\", q.array())\n",
"\n",
"vprev = None\n",
"while not q.empty():\n",
" v = q.remove()\n",
" print(v, end=\" \")\n",
" # Verify descending order of max_heap\n",
" assert((vprev is None) or (vprev >= v))\n",
" vprev = v\n",
"print()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.0"
},
"nikola": {
"category": "",
"date": "2018-10-18 06:43:20 UTC-06:00",
"description": "",
"link": "",
"slug": "binary-heaps",
"tags": "Python,Data Structures,Algorithms",
"title": "Binary Heaps",
"type": "text"
}
},
"nbformat": 4,
"nbformat_minor": 2
}