Presentation is loading. Please wait.

Presentation is loading. Please wait.

Section 10 Questions Heaps.

Similar presentations


Presentation on theme: "Section 10 Questions Heaps."— Presentation transcript:

1 Section 10 Questions Heaps

2 Questions Any?????

3 Heaps A tree containing numbers is a heap if:

4 Heaps A tree containing numbers is a heap if:
Every son has a value less than its parent.

5 Heaps Usually we also require them to be complete binary trees.
A complete binary tree - all the levels filled from left to right, the lowest one filled from left not necessarily to the end.

6 Complete binary tree

7 Complete binary tree

8 Implementation of heap operations
Get (returns the element with the highest numer) Put (inserts the element to the heap)

9 Implementations of heap operations
Get: Put:

10 Implementations of heap operations
Get: Take value from the top. Move the lowermost, rightmost element to its place. Move it down while necessary. (Heapify) Put: Put into the first free place in the last row. Move it up while necessary.

11 Time complexity Get: Put:

12 Time complexity Get: O(logn) - the height of the tree is log(n), since it’s complete, and you descend doing Heapify. Put: The same, from the same reason.

13 Heap implementation We do not have to use pointer structure.
We can use an array to implement a heap! How?

14 Heap implementation a[1] = root a[2,3] = its sons
a[4,5,6,7] = their sons a[8..15] = their sons etc.

15 Walking through a heap parent(a[i])? leftSon(a[i])? rightSon(a[i])?

16 Walking through a heap parent(a[i]) = a[i / 2] leftSon(a[i]) = a[i*2]
rightSon(a[i]) = a[i*2+1] Very efficient!

17 Heapsort Convert an array to the heap.
Repeatedly call get and put the result in the end of the array.

18 Heapsort Convert an array to the heap.
Repeatedly call get and put the result in the end of the array.

19 Converting array to the heap
The elements a[n/2..n] are leaves, we leave them in peace. For (i = n/2; i>=1;i--) heapify(a[i]) Time complexity: Can be shown to be O(n).

20 Heapsort complexity Convert an array to the heap - O(n)
Repeatedly call get and put the result in the end of the array - ???

21 Heapsort complexity Convert an array to the heap - O(n)
Repeatedly call get and put the result in the end of the array - O(nlog(n)) - each get takes O(logn), there are n gets. O(n) + O(nlog(n)) = O(nlog(n)) Very good!


Download ppt "Section 10 Questions Heaps."

Similar presentations


Ads by Google