10b - TreesSlides

# We exchange the first and last values since this

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

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: called Heapsort 0 7 All we have to do is have a way of finding the largest of the rest of the tree, removing the biggest each time. 5 1 2 2 7 4 3 3 4 5 6 1 7 Here's how we do it. Here's our previous example. We exchange the first and last values. Now the 8 is in its correct position in the array (last – we are sorting into increasing order). Tree now has one less value, i.e. n = 7. Now we remake the heap. remake Note remake not make, as all the subtrees are all make still heaps. 1 1 0 0 7 5 7 1 2 1 5 2 2 7 4 3 2 7 4 3 3 4 5 6 3 4 5 6 8 7 8 Cut it off the tree. 7 20 Now swap the first and last in the tree. 7 7 0 0 1 5 7 1 2 1 2 7 4 3 3 4 5 6 5 2 2 3 4 5 6 8 7 4 3 8 1 7 Now swap the first and last in the tree. And reduce the tree by one value. Now swap the first and last in the tree. And reduce the tree by one value. The rebuild required just MakeHeap(0). MakeHeap(0) 3 3 0 0 7 5 7 1 2 1 5 2 2 1 4 7 2 1 4 7 3 4 5 6 3 4 5 6 8 8 7 7 By the finish of the process, the data is sorted. The complete (recursive) build is only required once. All other rebuilds are just MakeHeap(0). MakeHeap(0) How efficient? efficient? It is O(n log n) as it uses a binary tree. But the improvement over Quicksort is that the worst case is O(n log n). 21...
View Full Document

## This document was uploaded on 04/07/2014.

Ask a homework question - tutors are online