PRIORITY QUEUES BINARY HEAP IMPLEMENTATION PRIORITY QUEUES Normal
PRIORITY QUEUES (BINARY HEAP IMPLEMENTATION)
PRIORITY QUEUES • Normal Queue: FIFO • Priority Queue: BO (Best Out) • Best = Lower : Min. Queue • Best = Higher: Max. Queue • Logically a loosely-sorted Tree • Internally an Array (of Comparables) • Strengths: • Low memory requirements • Plus: easy to convert a list / array to a heap • Fast push and pop performance • As a tree, it is self-balancing. • Weaknesses • Poor iteration, find performance
TREES IN GENERAL • We’ll explore in more detail next lab. • Basics: • • root children / descendants (connection to arity) leaf vs. inernal balanced vs. imbalanced
LOGICAL INTERNAL CONNECTION • Internal Storage: • An array (often with a "dummy" initial value) • Heap properties • The "tree" is always balanced • Adds happen at lowest-level, L => R • A node's descendants are always lower (for Max. Queue) valued. • The highest-value node is always the root (for Max. Queue) • If a Node has only one child it is always the left.
LOGICAL INTERNAL CONNECTION, CONT. null 43. 2 15. 1 13. 6 12. 4 14. 7 3. 2 12. 9 1. 3 0 4 5 6 7 1 2 3 8 Internal 43. 2 15. 1 13. 6 Logical 12. 4 14. 7 3. 2 12. 9 1. 3 • Note the difference between a Heap and a BST • Additional (important) Heap Properties: • parent. Index = child. Index >> 1 • left. Child. Index = parent. Index << 1 • right. Child. Index = left. Child. Index + 1
TANGENT: BIT-SHIFT OPERATORS • Every integer type (char, short, int, long) is stored in binary. • To convert decimal => binary, find powers of 2 that, added together, equal the decimal. • Place 1’s in those “slots” used, 0’s elsewhere • Generally, LSB (1’s place) is shown to the right • And MSB (128’s place for char) is shown to the left. • E. g. short x = 237; Place Value • 237 = 128 + 64 + 32 + 8 + 4 + 1 sign ~ 16384 0 8192 4096 2048 1024 512 256 128 0 0 0 1 64 32 16 1 1 0 64 32 16 1 0 1 8 4 2 1 1 1 0 1 • Bit-shifting shifts the binary digits that many places. e. g. x = x << 1; // now 474 Place Value sign ~ 16384 0 8192 4096 2048 1024 512 256 128 0 0 0 1 1 8 4 2 1 0 1 • Note how this in effect multiplies by 2! • Shifting 2 places would multiply by 4, 3 places by 8 and so on. • Why? • Does in one CPU clock tick what would take many (32 – 64) clock ticks! 1 0
PUSH PSEUDO-CODE def push (val): # For Max. Queue index = len(L) L. append(val) parent = index >> 1 while index >= 1 and L[index] > L[parent]: swap L[index] and L[parent] index = parent = index >> 1 On the board, trace through a few pushes.
POP PSEUDO-CODE def pop(): # For Max. Queue swap L[1] and L[len(L) – 1] val = L[len(L) – 1] L. remove(L[len(L) – 1]) index = 1 while L[index] < either child: child = larger-valued child index swap L[index] and L[child] index = child return val On the board, trace through a few pops.
OPTIONAL OPERATIONS • reheapify(int index) • reheapify()
BIG-O ANALYSIS •
- Slides: 10