COMPUTER S
chapter21

# chapter21 - Heaps Chapter 21 What is a heap used for...

• Notes
• 29

This preview shows pages 1–9. Sign up to view the full content.

Heaps Chapter 21

This preview has intentionally blurred sections. Sign up to view the full version.

What is a heap used for? Sorting HeapSort sorts an N -element array on O ( N log N ) time and uses very little extra memory Priority Queues Heaps allow inserting an element and extracting the smallest element in a set, both in O (log N ) time
What is a heap? A heap is a binary tree with two properties Order : the key at any node is less than or equal to the keys in the node’s children the least element is at the root of the tree there is no relative order of left and right children Shape : all leaves are on at most two levels, with those on the bottom level as far left as possible, and there are no “holes”

This preview has intentionally blurred sections. Sign up to view the full version.

Here is a heap of 12 integers
Implementing a heap There are many possible representations of binary trees The shape property allows us to use an array with the tree information only implicit in the representation

This preview has intentionally blurred sections. Sign up to view the full version.

A 12-element tree as an array
Operation on a tree with Shape Various functions on the tree are defined as follows: Root = 1 Key(i) = A[i] LeftChild(i) = 2*i RightChild(i) = 2*i+1 Parent(i) = i / 2 Null(i) = (i < 1) || (i > N)

This preview has intentionally blurred sections. Sign up to view the full version.

Representation 12 20 15 29 23 17 22 35 40 26 51 19 1 12
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### What students are saying

• As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

Kiran Temple University Fox School of Business ‘17, Course Hero Intern

• I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

Dana University of Pennsylvania ‘17, Course Hero Intern

• The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

Jill Tulane University ‘16, Course Hero Intern