Heaps Heaps n Definition A heap is a

  • Slides: 8
Download presentation
Heaps

Heaps

Heaps n Definition ¨A heap is a binary tree with these characteristics: It’s complete.

Heaps n Definition ¨A heap is a binary tree with these characteristics: It’s complete. This means it’s completely filled in, reading from left to right across each row, although the last row need not be full. (Example) fig 12. 1 in the page 580 n Each node in a heap satisfies the heap condition, which states that every node’s key is larger than (or equal to) the keys of its descendants. (Example) fig 12. 2 in the page 581 n

Heaps: Removal 1. 2. 3. Remove the root. Move the last node into the

Heaps: Removal 1. 2. 3. Remove the root. Move the last node into the root. Trickle (the terms bubble or percolate are also used) the last node down until it’s below a larger node and above a smaller one. See Remove method

Basic Operations & Key Change Basic Operations See Trickle Down method See Trickle Up

Basic Operations & Key Change Basic Operations See Trickle Down method See Trickle Up method See Key Change method

Insertion 1. 2. the node to be inserted is placed in the first open

Insertion 1. 2. the node to be inserted is placed in the first open position at the end of the array Trickle the inserted node up until it’s below a larger node and above a smaller one. See Insert method

Heapsort [Basic Idea] insert all the unordered items into a heap using the normal

Heapsort [Basic Idea] insert all the unordered items into a heap using the normal insert() routine. 2. repeated application of the remove() routine will then remove the items in sorted order. 1. for (j = 0; j < size; j++) the. Heap. insert(an. Array[j]); //from unsorted array for (j = 0; j < size; j++) an. Array[j] = the. Heap. remove(); // to sorted array

Efficiency n Efficiency of the heapsort ¨ Expected case: O(N*log. N) ¨ Worst case:

Efficiency n Efficiency of the heapsort ¨ Expected case: O(N*log. N) ¨ Worst case: O(N*log. N) n cf. Quicksort ¨ Expected case: O(N*log. N) ¨ Worst case: O(N 2)

Recursive Approach [Recursive Approach] n Observation: Two correct subheaps make a correct heap. (Example)

Recursive Approach [Recursive Approach] n Observation: Two correct subheaps make a correct heap. (Example) fig 12. 8 in the page 602 n See Heapify method ¨ Transform array into heap