Midterm Review. EECS 2011 Prof. J. Elder - 1 -

Similar documents
Midterm Review. EECS 2011 Prof. J. Elder - 1 -

Priority Queues & Heaps

Priority Queues & Heaps

Priority Queues & Heaps

Search Trees. Chapter 10. CSE 2011 Prof. J. Elder Last Updated: :51 PM

ECE250: Algorithms and Data Structures Trees

Maps and Hash Tables. EECS 2011 Prof. J. Elder - 1 -

Maps, Hash Tables and Dictionaries

Comparison Sorts. EECS 2011 Prof. J. Elder - 1 -

File Systems: Fundamentals

COMP : DATA STRUCTURES 2/27/14. Are binary trees satisfying two additional properties:

TAFTW (Take Aways for the Week) APT Quiz and Markov Overview. Comparing objects and tradeoffs. From Comparable to TreeMap/Sort

Chapter 8: Recursion

Proving correctness of Stable Matching algorithm Analyzing algorithms Asymptotic running times

Estimating the Margin of Victory for Instant-Runoff Voting

CS 5523: Operating Systems

Optimization Strategies

Uninformed search. Lirong Xia

Constraint satisfaction problems. Lirong Xia

Hoboken Public Schools. Algebra II Honors Curriculum

Contents. Bibliography 121. Index 123

NEW YORK CITY COLLEGE OF TECHNOLOGY The City University of New York

Data 100. Lecture 9: Scraping Web Technologies. Slides by: Joseph E. Gonzalez, Deb Nolan

Hoboken Public Schools. College Algebra Curriculum

Chapter 11. Weighted Voting Systems. For All Practical Purposes: Effective Teaching

Notes for Session 7 Basic Voting Theory and Arrow s Theorem

Event Based Sequential Program Development: Application to Constructing a Pointer Program

A Calculus for End-to-end Statistical Service Guarantees

Complexity of Manipulating Elections with Few Candidates

Text UI. Data Store Ø Example of a backend to a real Could add a different user interface. Good judgment comes from experience

Approval Voting Theory with Multiple Levels of Approval

The Effectiveness of Receipt-Based Attacks on ThreeBallot

Mathematics and Social Choice Theory. Topic 4 Voting methods with more than 2 alternatives. 4.1 Social choice procedures

One View Watchlists Implementation Guide Release 9.2

Estimating the Margin of Victory for an IRV Election Part 1 by David Cary November 6, 2010

General Framework of Electronic Voting and Implementation thereof at National Elections in Estonia

Primecoin: Cryptocurrency with Prime Number Proof-of-Work

Year 1 Mental mathematics and fluency in rapid recall of number facts are one of the main aims of the new Mathematics Curriculum.

Estonian National Electoral Committee. E-Voting System. General Overview

Cluster Analysis. (see also: Segmentation)

This situation where each voter is not equal in the number of votes they control is called:

Swiss E-Voting Workshop 2010

Introduction to Game Theory. Lirong Xia

Please reach out to for a complete list of our GET::search method conditions. 3

IBM Cognos Open Mic Cognos Analytics 11 Part nd June, IBM Corporation

Batch binary Edwards. D. J. Bernstein University of Illinois at Chicago NSF ITR

Exploring QR Factorization on GPU for Quantum Monte Carlo Simulation

Fall 2016 COP 3223H Program #5: Election Season Nears an End Due date: Please consult WebCourses for your section

Lecture 6 Cryptographic Hash Functions

Hoboken Public Schools. Algebra I Curriculum

Processes. Criteria for Comparing Scheduling Algorithms

Hoboken Public Schools. Project Lead The Way Curriculum Grade 8

Support Vector Machines

Bribery in voting with CP-nets

Classifier Evaluation and Selection. Review and Overview of Methods

Electrical Engineering and Computer Science Department

New Hampshire Secretary of State Electronic Ballot Counting Devices

Louis M. Edwards Mathematics Super Bowl Valencia Community College -- April 30, 2004

Subreddit Recommendations within Reddit Communities

VOTING DYNAMICS IN INNOVATION SYSTEMS

A Bloom Filter Based Scalable Data Integrity Check Tool for Large-scale Dataset

Title: Adverserial Search AIMA: Chapter 5 (Sections 5.1, 5.2 and 5.3)

PCGENESIS PAYROLL SYSTEM OPERATIONS GUIDE

OPEN SOURCE CRYPTOCURRENCY

JD Edwards EnterpriseOne Applications

MATH4999 Capstone Projects in Mathematics and Economics Topic 3 Voting methods and social choice theory

Title: Solving Problems by Searching AIMA: Chapter 3 (Sections 3.1, 3.2 and 3.3)

Random Forests. Gradient Boosting. and. Bagging and Boosting

Case Study. MegaMatcher Accelerator

GST 104: Cartographic Design Lab 6: Countries with Refugees and Internally Displaced Persons Over 1 Million Map Design

Many Social Choice Rules

Polydisciplinary Faculty of Larache Abdelmalek Essaadi University, MOROCCO 3 Department of Mathematics and Informatics

M-Series, Actuator Overview. Machine Screw Cutaway. UNI-LIFT Machine Screw Actuators offer precise. 12

Protocol to Check Correctness of Colorado s Risk-Limiting Tabulation Audit

Homework 4 solutions

ANALYSES OF JUVENILE CHINOOK SALMON AND STEELHEAD TRANSPORT FROM LOWER GRANITE AND LITTLE GOOSE DAMS, NOAA Fisheries

CSCI211: Intro Objectives

CS 5523 Operating Systems: Synchronization in Distributed Systems

arxiv: v2 [math.ho] 12 Oct 2018

B-Series Section Overview. Ball Screw Cutaway. UNI-LIFT Ball Screw Actuators provide high. 34

Social welfare functions

Overview. Ø Neural Networks are considered black-box models Ø They are complex and do not provide much insight into variable relationships

Andreas Fring. Basic Operations

HASHGRAPH CONSENSUS: DETAILED EXAMPLES

IC Chapter 15. Ballot Card and Electronic Voting Systems; Additional Standards and Procedures for Approving System Changes

Genetic Algorithms with Elitism-Based Immigrants for Changing Optimization Problems

Introduction to Path Analysis: Multivariate Regression

Chief Electoral Officer Directives for the Counting of Ballots (Elections Act, R.S.N.B. 1973, c.e-3, ss.5.2(1), s.87.63, 87.64, 91.1, and 91.

WORLD INTELLECTUAL PROPERTY ORGANIZATION GENEVA SPECIAL UNION FOR THE INTERNATIONAL PATENT CLASSIFICATION (IPC UNION) AD HOC IPC REFORM WORKING GROUP

COULD SIMULATION OPTIMIZATION HAVE PREVENTED 2012 CENTRAL FLORIDA ELECTION LINES?

Iowa Voting Series, Paper 6: An Examination of Iowa Absentee Voting Since 2000

Case 4:16-cv Document 11 Filed in TXSD on 08/15/16 Page 1 of 32 IN UNITED STATES DISTRICT COURT FOR THE SOUTHERN DISTRICT OF TEXAS

Photon Identification in the Future. Andrew Askew Florida State University

ForeScout Extended Module for McAfee epolicy Orchestrator

The mathematics of voting, power, and sharing Part 1

MOS Exams Objective Mapping

NELIS NEVADA ELECTRONIC LEGISLATIVE INFORMATION SYSTEM 79TH (2017) SESSION

Please see my attached comments. Thank you.

Tengyu Ma Facebook AI Research. Based on joint work with Yuanzhi Li (Princeton) and Hongyang Zhang (Stanford)

Super-Simple Simultaneous Single-Ballot Risk-Limiting Audits

Transcription:

Midterm Review - 1 -

Topics on the Midterm Ø Data Structures & Object-Oriented Design Ø Run-Time Analysis Ø Linear Data Structures Ø The Java Collections Framework Ø Recursion Ø Trees Ø Priority Queues & Heaps - 2 -

Data Structures So Far Ø Array List q (Extendable) Array Ø Node List q Singly or Doubly Linked List Ø Stack q Array q Singly Linked List Ø Queue q Array q Singly or Doubly Linked List Ø Priority Queue q Unsorted doubly-linked list q Sorted doubly-linked list q Heap (array-based) Ø Adaptable Priority Queue Ø Tree q Sorted doubly-linked list with locationaware entries q Heap with location-aware entries q Linked Structure Ø Binary Tree q Linked Structure q Array - 3 -

Topics on the Midterm Ø Data Structures & Object-Oriented Design Ø Run-Time Analysis Ø Linear Data Structures Ø The Java Collections Framework Ø Recursion Ø Trees Ø Priority Queues & Heaps - 4 -

Data Structures & Object-Oriented Design Ø Definitions Ø Principles of Object-Oriented Design Ø Hierarchical Design in Java Ø Abstract Data Types & Interfaces Ø Casting Ø Generics Ø Pseudo-Code - 5 -

Ø Software must be: q Readable and understandable Software Engineering ² Allows correctness to be verified, and software to be easily updated. q Correct and complete ² Works correctly for all expected inputs q Robust ² Capable of handling unexpected inputs. q Adaptible ² All programs evolve over time. Programs should be designed so that re-use, generalization and modification is easy. q Portable ² Easily ported to new hardware or operating system platforms. q Efficient ² Makes reasonable use of time and memory resources. - 6 -

Seven Important Functions Ø Seven functions that often appear in algorithm analysis: q Constant 1 q Logarithmic log n q Linear n q N-Log-N n log n q Quadratic n 2 q Cubic n 3 q Exponential 2 n Ø In a log-log chart, the slope of the line corresponds to the growth rate of the function. - 7 -

Topics on the Midterm Ø Data Structures & Object-Oriented Design Ø Run-Time Analysis Ø Linear Data Structures Ø The Java Collections Framework Ø Recursion Ø Trees Ø Priority Queues & Heaps - 8 -

Some Math to Review " Summations Ø properties of logarithms: " Logarithms and Exponents log b (xy) = log b x + log b y " Existential and universal operators " Proof techniques log b (x/y) = log b x - log b y " Basic probability log b x a = alog b x log b a = log x a/log x b existential and universal operators g b Loves(b, g) g b Loves(b, g) Ø properties of exponentials: a (b+c) = a b a c a bc = (a b ) c a b /a c = a (b-c) b = a log a b b c = a c*log a b - 9 -

Definition of Big Oh cg( n) fn ( ) fn ( ) Ogn ( ( )) gn ( ) > cn, 0 0: n n0, f( n) cgn ( ) n - 10 -

Arithmetic Progression Ø The running time of prefixaverages1 is O(1 + 2 + + n) Ø The sum of the first n integers is n(n + 1) / 2 q There is a simple visual proof of this fact Ø Thus, algorithm prefixaverages1 runs in O(n 2 ) time 7 6 5 4 3 2 1 0 1 2 3 4 5 6-11 -

Relatives of Big-Oh " big-omega n f(n) is Ω(g(n)) if there is a constant c > 0 and an integer constant n 0 1 such that f(n) c g(n) for n n 0 " big-theta n f(n) is Θ(g(n)) if there are constants c 1 > 0 and c 2 > 0 and an integer constant n 0 1 such that c 1 g(n) f(n) c 2 g(n) for n n 0-12 -

Time Complexity of an Algorithm The time complexity of an algorithm is the largest time required on any input of size n. (Worst case analysis.) Ø O(n 2 ): For any input size n n 0, the algorithm takes no more than cn 2 time on every input. Ø Ω(n 2 ): For any input size n n 0, the algorithm takes at least cn 2 time on at least one input. Ø θ (n 2 ): Do both. - 13 -

Time Complexity of a Problem The time complexity of a problem is the time complexity of the fastest algorithm that solves the problem. Ø O(n 2 ): Provide an algorithm that solves the problem in no more than this time. q Remember: for every input, i.e. worst case analysis! Ø Ω(n 2 ): Prove that no algorithm can solve it faster. q Remember: only need one input that takes at least this long! Ø θ (n 2 ): Do both. - 14 -

Topics on the Midterm Ø Data Structures & Object-Oriented Design Ø Run-Time Analysis Ø Linear Data Structures Ø The Java Collections Framework Ø Recursion Ø Trees Ø Priority Queues & Heaps - 15 -

Arrays - 16 -

Arrays Ø Array: a sequence of indexed components with the following properties: q array size is fixed at the time of array s construction ² int[] numbers = new int [10]; q array elements are placed contiguously in memory ² address of any element can be calculated directly as its offset from the beginning of the array q consequently, array components can be efficiently inspected or updated in O(1) time, using their indices ² randomnumber = numbers[5]; ² numbers[2] = 100; - 17 -

Arrays in Java Ø Since an array is an object, the name of the array is actually a reference (pointer) to the place in memory where the array is stored. q reference to an object holds the address of the actual object Ø Example [ arrays as objects] int[] A={12, 24, 37, 53, 67}; int[] B=A; B[3]=5; Ø Example [ cloning an array] int[] A={12, 24, 37, 53, 67}; int[] B=A.clone(); B[3]=5; A B A B A B A B - 18-12 24 37 53 67 12 24 37 5 67 12 24 37 53 67 12 24 37 53 67 12 24 37 53 67 12 24 37 5 67

Example Example [ 2D array in Java = array of arrays] int[][] nums = new int[5][4]; int[][] nums; nums = new int[5][]; for (int i=0; i<5; i++) { nums[i] = new int[4]; } - 19 -

Array Lists - 20 -

The Array List ADT ( 6.1) Ø The Array List ADT extends the notion of array by storing a sequence of arbitrary objects Ø An element can be accessed, inserted or removed by specifying its rank (number of elements preceding it) Ø An exception is thrown if an incorrect rank is specified (e.g., a negative rank) - 21 -

The Array List ADT public interface IndexList<E> { /** Returns the number of elements in this list */ public int size(); /** Returns whether the list is empty. */ public boolean isempty(); /** Inserts an element e to be at index I, shifting all elements after this. */ public void add(int I, E e) throws IndexOutOfBoundsException; /** Returns the element at index I, without removing it. */ public E get(int i) throws IndexOutOfBoundsException; /** Removes and returns the element at index I, shifting the elements after this. */ public E remove(int i) throws IndexOutOfBoundsException; /** Replaces the element at index I with e, returning the previous element at i. */ public E set(int I, E e) throws IndexOutOfBoundsException; } - 22 -

Performance Ø In the array based implementation q The space used by the data structure is O(n) q size, isempty, get and set run in O(1) time q add and remove run in O(n) time Ø In an add operation, when the array is full, instead of throwing an exception, we could replace the array with a larger one. Ø In fact java.util.arraylist implements this ADT using extendable arrays that do just this. - 23 -

Doubling Strategy Analysis Ø We replace the array k = log 2 n times Ø The total time T(n) of a series of n add(o) operations is proportional to n + 1 + 2 + 4 + 8 + + 2 k = n + 2 k + 1-1 = 2n -1 Ø Thus T(n) is O(n) Ø The amortized time of an add operation is O(1)! geometric series 2 4 1 1 8 Recall: n r i = i =0 n+1 1 r 1 r - 24 -

Stacks Chapter 5.1-25 -

The Stack ADT Ø The Stack ADT stores arbitrary objects Ø Insertions and deletions follow the last-in first-out scheme Ø Think of a spring-loaded plate dispenser Ø Main stack operations: q push(object): inserts an element q object pop(): removes and returns the last inserted element Ø Auxiliary stack operations: q object top(): returns the last inserted element without removing it q integer size(): returns the number of elements stored q boolean isempty(): indicates whether no elements are stored - 26 -

Array-based Stack Ø A simple way of implementing the Stack ADT uses an array Ø We add elements from left to right Ø A variable keeps track of the index of the top element Algorithm size() return t + 1 Algorithm pop() if isempty() then throw EmptyStackException else t ç t - 1 return S[t + 1] S 0 1 2 t - 27 -

Queues Chapters 5.2-5.3-28 -

Array-Based Queue Ø Use an array of size N in a circular fashion Ø Two variables keep track of the front and rear f index of the front element r index immediately past the rear element Ø Array location r is kept empty Q normal configuration 0 1 2 f r Q wrapped-around configuration 0 1 2 r f - 29 -

Queue Operations Ø We use the modulo operator (remainder of division) Algorithm size() return (N - f + r) mod N Algorithm isempty() return (f = r) Note: N f + r = (r + N) f Q 0 1 2 f r Q 0 1 2 r f - 30 -

Linked Lists Chapters 3.2 3.3-31 -

Singly Linked List ( 3.2) Ø A singly linked list is a concrete data structure consisting of a sequence of nodes Ø Each node stores q element q link to the next node elem next node A B C D - 32 -

Running Time Ø Adding at the head is O(1) Ø Removing at the head is O(1) Ø How about tail operations? - 33 -

Doubly Linked List Ø Doubly-linked lists allow more flexible list management (constant time operations at both ends). Ø Nodes store: q element q link to the previous node prev next q link to the next node Ø Special trailer and header (sentinel) nodes elem node header nodes/positions trailer - 34 - elements

Topics on the Midterm Ø Data Structures & Object-Oriented Design Ø Run-Time Analysis Ø Linear Data Structures Ø The Java Collections Framework Ø Recursion Ø Trees Ø Priority Queues & Heaps - 35 -

Iterators Ø An Iterator is an object that enables you to traverse through a collection and to remove elements from the collection selectively, if desired. Ø You get an Iterator for a collection by calling its iterator method. Ø Suppose collection is an instance of a Collection. Then to print out each element on a separate line: Iterator<E> it = collection.iterator(); while (it.hasnext()) System.out.println(it.next()); - 36 -

The Java Collections Framework (Ordered Data Types) Interface Abstract Class Class Iterable Collection Queue Abstract Collection List Abstract Queue Abstract List Priority Queue Abstract Sequential List Array List Vector Stack Linked List - 37 -

Topics on the Midterm Ø Data Structures & Object-Oriented Design Ø Run-Time Analysis Ø Linear Data Structures Ø The Java Collections Framework Ø Recursion Ø Trees Ø Priority Queues & Heaps - 38 -

Linear Recursion Design Pattern Ø Test for base cases q Begin by testing for a set of base cases (there should be at least one). q Every possible chain of recursive calls must eventually reach a base case, and the handling of each base case should not use recursion. Ø Recurse once q Perform a single recursive call. (This recursive step may involve a test that decides which of several possible recursive calls to make, but it should ultimately choose to make just one of these calls each time we perform this step.) q Define each possible recursive call so that it makes progress towards a base case. - 39 -

Binary Recursion Ø Binary recursion occurs whenever there are two recursive calls for each non-base case. Ø Example 1: The Fibonacci Sequence - 40 -

Formal Definition of Rooted Tree Ø A rooted tree may be empty. Ø Otherwise, it consists of q A root node r q A set of subtrees whose roots are the children of r r B C D E F G H - 41 - I J K subtree

Topics on the Midterm Ø Data Structures & Object-Oriented Design Ø Run-Time Analysis Ø Linear Data Structures Ø The Java Collections Framework Ø Recursion Ø Trees Ø Priority Queues & Heaps - 42 -

Tree Terminology Ø Root: node without parent (A) Ø Internal node: node with at least one child (A, B, C, F) Ø External node (a.k.a. leaf ): node without children (E, I, J, K, G, H, D) Ø Ancestors of a node: parent, grandparent, grand-grandparent, etc. A Ø Descendant of a node: child, grandchild, grand-grandchild, etc. Ø Siblings: two nodes having the same parent B C D Ø Depth of a node: number of ancestors (excluding self) E F G H Ø Height of a tree: maximum depth of any node (3) Ø Subtree: tree consisting of a node and its descendants I J K subtree - 43 -

Position ADT Ø The Position ADT models the notion of place within a data structure where a single object is stored Ø It gives a unified view of diverse ways of storing data, such as q a cell of an array q a node of a linked list q a node of a tree Ø Just one method: q object element(): returns the element stored at the position - 44 -

Tree ADT Ø We use positions to abstract nodes Ø Generic methods: q integer size() q boolean isempty() q Iterator iterator() q Iterable positions() Ø Accessor methods: q position root() q position parent(p) q positioniterator children(p) Ø Query methods: q boolean isinternal(p) q boolean isexternal(p) q boolean isroot(p) Ø Update method: q object replace(p, o) q Additional update methods may be defined by data structures implementing the Tree ADT - 45 -

Preorder Traversal Ø A traversal visits the nodes of a tree in a systematic manner Ø In a preorder traversal, a node is visited before its descendants Algorithm preorder(v) visit(v) for each child w of v preorder (w) 1 Make Money Fast! 2 1. Motivations 2. Methods References 5 9 3 4 1.1 Greed 1.2 Avidity 6 7 8 2.1 Stock Fraud 2.2 Ponzi Scheme 2.3 Bank Robbery - 46 -

Postorder Traversal Ø In a postorder traversal, a node is visited after its descendants Algorithm postorder(v) for each child w of v postorder (w) visit(v) 9 cs16/ 3 homeworks/ 7 programs/ 8 todo.txt 1K 1 2 4 5 6 h1c.doc 3K h1nc.doc 2K DDR.java 10K Stocks.java 25K Robot.java 20K - 47 -

Properties of Proper Binary Trees Ø Notation n number of nodes e number of external nodes i number of internal nodes h height Ø Properties: q e = i + 1 q n = 2e - 1 q h i q h (n - 1)/2 q e 2 h q h log 2 e q h log 2 (n + 1) - 1-48 -

BinaryTree ADT Ø The BinaryTree ADT extends the Tree ADT, i.e., it inherits all the methods of the Tree ADT Ø Additional methods: q position left(p) q position right(p) q boolean hasleft(p) q boolean hasright(p) Ø Update methods may be defined by data structures implementing the BinaryTree ADT - 49 -

Topics on the Midterm Ø Data Structures & Object-Oriented Design Ø Run-Time Analysis Ø Linear Data Structures Ø The Java Collections Framework Ø Recursion Ø Trees Ø Priority Queues & Heaps - 50 -

Priority Queue ADT Ø A priority queue stores a collection of entries Ø Each entry is a pair (key, value) Ø Main methods of the Priority Queue ADT q insert(k, x) inserts an entry with key k and value x q removemin() removes and returns the entry with smallest key Ø Additional methods q min() returns, but does not remove, an entry with smallest key q size(), isempty() Ø Applications: q Process scheduling q Standby flyers - 51 -

Entry ADT Ø An entry in a priority queue is simply a keyvalue pair Ø Methods: q key(): returns the key for this entry q value(): returns the value for this entry Ø As a Java interface: /** * Interface for a key-value * pair entry **/ public interface Entry { public Object key(); public Object value(); } - 52 -

Comparator ADT Ø A comparator encapsulates the action of comparing two objects according to a given total order relation Ø A generic priority queue uses an auxiliary comparator Ø The comparator is external to the keys being compared Ø When the priority queue needs to compare two keys, it uses its comparator Ø The primary method of the Comparator ADT: q compare(a, b): ² Returns an integer i such that v i < 0 if a < b v i = 0 if a = b v i > 0 if a > b v an error occurs if a and b cannot be compared. - 53 -

Sequence-based Priority Queue Ø Implementation with an unsorted list Ø Implementation with a sorted list 4 5 2 3 1 1 2 3 4 5 Ø Performance: q insert takes O(1) time since we can insert the item at the beginning or end of the sequence q removemin and min take O(n) time since we have to traverse the entire sequence to find the smallest key Ø Performance: q insert takes O(n) time since we have to find the right place to insert the item q removemin and min take O(1) time, since the smallest key is at the beginning Is this tradeoff inevitable? - 54 -

Heaps Ø Goal: q O(log n) insertion q O(log n) removal Ø Remember that O(log n) is almost as good as O(1)! q e.g., n = 1,000,000,000 à log n 30 Ø There are min heaps and max heaps. We will assume min heaps. - 55 -

Min Heaps Ø A min heap is a binary tree storing keys at its nodes and satisfying the following properties: q Heap-order: for every internal node v other than the root ² key(v) key(parent(v)) q (Almost) complete binary tree: let h be the height of the heap ² for i = 0,, h - 1, there are 2 i nodes of depth i ² at depth h 1 v the internal nodes are to the left of the external nodes v Only the rightmost internal node may have a single child 2 5 6 9 7-56 - q The last node of a heap is the rightmost node of depth h

Upheap Ø After the insertion of a new key k, the heap-order property may be violated Ø Algorithm upheap restores the heap-order property by swapping k along an upward path from the insertion node Ø Upheap terminates when the key k reaches the root or a node whose parent has a key smaller than or equal to k Ø Since a heap has height O(log n), upheap runs in O(log n) time 2 1 5 1 5 2 9 7 6 9 7 6-57 -

Downheap Ø After replacing the root key with the key k of the last node, the heap-order property may be violated Ø Algorithm downheap restores the heap-order property by swapping key k along a downward path from the root Ø Note that there are, in general, many possible downward paths which one do we choose??? 7 5 w 6 9-58 -

Downheap Ø We select the downward path through the minimum-key nodes. Ø Downheap terminates when key k reaches a leaf or a node whose children have keys greater than or equal to k Ø Since a heap has height O(log n), downheap runs in O(log n) time 7 5 5 w 6 7 w 6 9 9-59 -

Array-based Heap Implementation Ø We can represent a heap with n keys by means of an array of length n + 1 Ø Links between nodes are not explicitly stored 2 Ø The cell at rank 0 is not used Ø The root is stored at rank 1. Ø For the node at rank i q the left child is at rank 2i q the right child is at rank 2i + 1 9 5 7 6 q the parent is at rank floor(i/2) q if 2i + 1 > n, the node has no right child q if 2i > n, the node is a leaf 0 2 5 6 9 7 1 2 3 4 5-60 -

Bottom-up Heap Construction Ø We can construct a heap storing n keys using a bottom-up construction with log n phases 2 i -1 2 i -1 Ø In phase i, pairs of heaps with 2 i -1 keys are merged into heaps with 2 i+1-1 keys Ø Run time for construction is O(n). 2 i+1-1 - 61 -

Adaptable Priority 3 a Queues 5 g 4 e - 62 -

Additional Methods of the Adaptable Priority Queue ADT Ø remove(e): Remove from P and return entry e. Ø replacekey(e,k): Replace with k and return the old key; an error condition occurs if k is invalid (that is, k cannot be compared with other keys). Ø replacevalue(e,x): Replace with x and return the old value. - 63 -

Location-Aware Entries Ø A locator-aware entry identifies and tracks the location of its (key, value) object within a data structure - 64 -

List Implementation Ø A location-aware list entry is an object storing q key q value q position (or rank) of the item in the list Ø In turn, the position (or array cell) stores the entry Ø Back pointers (or ranks) are updated during swaps header nodes/positions trailer 2 c 4 a 5 d 8 b - 65 - entries

Heap Implementation Ø A location-aware heap entry is an object storing q key 2 d q value q position of the entry in the underlying heap Ø In turn, each heap position stores an entry Ø Back pointers are updated during entry swaps 4 a 6 b 8 g 5 e 9 c - 66 -

Performance Ø Times better than those achievable without location-aware entries are highlighted in red: Method Unsorted List Sorted List Heap size, isempty O(1) O(1) O(1) insert O(1) O(n) O(log n) min O(n) O(1) O(1) removemin O(n) O(1) O(log n) remove O(1) O(1) O(log n) replacekey O(1) O(n) O(log n) replacevalue O(1) O(1) O(1) - 67 -

Topics on the Midterm Ø Data Structures & Object-Oriented Design Ø Run-Time Analysis Ø Linear Data Structures Ø The Java Collections Framework Ø Recursion Ø Trees Ø Priority Queues & Heaps - 68 -