{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Binary Heap Implementation\n", "\n", "Here is the reference code for the Binary Heap Implementation. Make sure to refer to the video lecture for the full explanation!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Binary Heap Operations\n", "**The basic operations we will implement for our binary heap are as follows:**\n", "\n", "* BinaryHeap() creates a new, empty, binary heap.\n", "* insert(k) adds a new item to the heap.\n", "* findMin() returns the item with the minimum key value, leaving item in the heap.\n", "* delMin() returns the item with the minimum key value, removing the item from the heap.\n", "* isEmpty() returns true if the heap is empty, false otherwise.\n", "* size() returns the number of items in the heap.\n", "* buildHeap(list) builds a new heap from a list of keys." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class BinHeap:\n", " def __init__(self):\n", " self.heapList = [0]\n", " self.currentSize = 0\n", "\n", "\n", " def percUp(self,i):\n", " \n", " while i // 2 > 0:\n", " \n", " if self.heapList[i] < self.heapList[i // 2]:\n", " \n", " \n", " tmp = self.heapList[i // 2]\n", " self.heapList[i // 2] = self.heapList[i]\n", " self.heapList[i] = tmp\n", " i = i // 2\n", "\n", " def insert(self,k):\n", " \n", " self.heapList.append(k)\n", " self.currentSize = self.currentSize + 1\n", " self.percUp(self.currentSize)\n", "\n", " def percDown(self,i):\n", " \n", " while (i * 2) <= self.currentSize:\n", " \n", " mc = self.minChild(i)\n", " if self.heapList[i] > self.heapList[mc]:\n", " \n", " tmp = self.heapList[i]\n", " self.heapList[i] = self.heapList[mc]\n", " self.heapList[mc] = tmp\n", " i = mc\n", "\n", " def minChild(self,i):\n", " \n", " if i * 2 + 1 > self.currentSize:\n", " \n", " return i * 2\n", " else:\n", " \n", " if self.heapList[i*2] < self.heapList[i*2+1]:\n", " return i * 2\n", " else:\n", " return i * 2 + 1\n", "\n", " def delMin(self):\n", " retval = self.heapList[1]\n", " self.heapList[1] = self.heapList[self.currentSize]\n", " self.currentSize = self.currentSize - 1\n", " self.heapList.pop()\n", " self.percDown(1)\n", " return retval\n", "\n", " def buildHeap(self,alist):\n", " i = len(alist) // 2\n", " self.currentSize = len(alist)\n", " self.heapList = [0] + alist[:]\n", " while (i > 0):\n", " self.percDown(i)\n", " i = i - 1" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.11" } }, "nbformat": 4, "nbformat_minor": 0 }