An an ascending priority queue can also can be be

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 14 Selection Sorts, ascending ! An An ascending priority queue can also can be be used: Initialize (PQueue) // ascending for for i ← 0 to n-1 // insert r[i] with priority k[i] Insert(PQueue, r[i], k[i]) for for i ← 0 to n-1 r[i] r[i] ← Remove(PQueue) 15 Heap Heap as a priority queue ! Heaps Heaps are efficient implementation of priority priority queues – Insert (at rear), expected complexity: Insert O(log n) (log – Remove (from front), expected Remove complexity: O(log n) (log – Access to front element: O(1) Access – Access to rear element: O(1) Access 16 Heap: Heap: Tree as an array ! Recall, Recall, the nodes of an almost complete BT can be stored in an array with the following scheme: scheme: – Index of parent = (index of child -1)/2 Index – Index of left child = 2 * index of parent + 1 – Index of right child = 2 * index of parent + 2 18 15 8 4 17 14 3 14 9 17 Max Max heap ! In In a max heap, the values of the two children are are equal to less than the value of the parent ! Example: array { 18, 15, 17, 8, 14, 14, 9, 4, 3} 18 15 8 4 ! 17 14 14 9 3 The The root always contains the maximum value (accessible in O(1)) 18 Max Max heap: insert element ! Insert new element: 16 – Put the new element at the end of the array (the Put next next leaf node): 18 15 8 4 17 14 3 14 9 16 19 Max Max heap: insert element – “sift up” the new element by swapping with the “sift parent’s element as long as the parent’s value is smaller: smaller: 18 15 8 4 17 14 3 14 9 16 20 Max Max heap: insert element – “sift up” the new element by swapping with the “sift parent’s element as long as the parent’s value is smaller: smaller: 18 15 17 16 8 4 3 14 9 14 21 Max Max heap: insert element – If the parent’s element value is greater or equal, If process process is complete 18 16 8 4 17 15 3 14 9 14 New New array: { 18, 16, 17, 8...
View Full Document

This document was uploaded on 03/06/2014 for the course ECE 368 at Purdue University-West Lafayette.

Ask a homework question - tutors are online