Transcript

Use with ChatGPT / Claude Auto-scroll A

1. Chapter 1 (0:12)

0:12 - 1:17
All right, welcome back to 6.006 data structures.Uh today we're going to cover a different kind of tree-like data structure called a heap, binary heap.It's going to let us solve sorting problem in a new way.Uh let me first remind you of a portion.The problem we're going to be solving today is called priority queue.This is the interface.We'll see several data structures, but one main data structure for today.Um and this is a subset of the set interface.And subsets are interesting because potentially we can solve them better, faster, simpler, something.Uh and so uh you'll recognize You should recognize all of these operations, except we don't We didn't normally highlight the max operation.So, here we're interested in storing a bunch of items.They have keys, uh which we think of as priorities, and we want to be able to identify the maximum priority item in our set, and remove it.
And so, there's lots of motivations for this.Maybe you have a router, packets going into the router, they have different priorities assigned to them.You want to route the highest priority first.Or you have processes on your computer running trying to run on your single-threaded uh single-core, and you've got to choose which one to run next, and you usually run higher priority processes first.Or you're trying to simulate uh a system where events happen at different times, and you want to process the next event ordered by time.All of these are examples of the priority queue interface.We'll even see applications within this class when we get to graph algorithms.Uh but the general The main two things we want to be able to support are inserting an item, which includes a key, and deleting the maximum item and also returning it at the same time.
Uh we'll also talk some about being able to build the structure faster than just inserting it, but of course we could implement build by starting empty and repeatedly inserting.Uh and also the complexity of just finding the max without deleting it.This you could simulate with these two operations by deleting the max and then reinserting it.Uh which works, uh but often we can do faster.Okay, but the two key main operations are insert and delete max, and we're going to see a few data structures to do this.Uh any suggestions?Among the data structures we've seen in this class, what should we use to solve priority queue interface?

2. Chapter 2 (2:50)

min pileAny possible answers?
Sequence AVL.Oh, that's interesting.Uh sequence AVL is a good answer, but uh that's maybe the fancier version that uh yeah.Set AVL sounds good.Uh set AVL supports these operations and many more, all in log n time except for build, which takes n log n time cuz you have to sort first.Uh so set AVL is a good good way to do this.We'll talk We'll come back to your sequence AVL idea later.Uh this gets log n per operation.Great.I mean, this is set AVL is our most powerful data structure.It does all the operations we care about uh on the set side, and the sequence AVL does all the operations on the sequence side, but note that this is a set, not a sequence.We care about keys.There are hacks to get around that with sequence AVL's, but let's do that later.
Um So great.If we uh wanted to, for example, speed up find max in a set AVL, we could add augmentation.We could um Remember subtree property augmentations?We can use that to get constant time find max by storing in every node the maximum key item within the subtree.And that's the subtree property, it's one we mentioned last class, so we could even improve that to constant time.Great.Um So we're done, end of lecture.Uh in some sense that's true, uh but what we're going to see today is another data structure called a binary heap, which is in some sense a simplification of set AVL.It achieves basically the same time bounds, build will be faster um by a log factor, but that's not the main reason we care about them.Uh the main advantage is that they're simpler and they give us uh an in-place sorting algorithm.
So uh I have up here the three of the operations I've been talking about, build, insert, and delete max.Uh so we have set AVL trees there, n log n build, log n insert, log n delete.Uh so along the way to our heap, I want to mention two other data structures.One is a dynamic but unsorted array, and the other is a dynamic sorted array.

3. Chapter 3 (5:25)

These are simpler data structures we've talked about many times before, and they're useful kind of motivations for getting started, because a heap is going to be built on top of arrays instead of Well, it's sort of a fusionbetween arrays and trees.So um if I have an unsorted array, this is very easy to insert into, right?Uh I just append to the end.This is what we called insert last.So, insert is fast, constant amortized.We might have to resize the array, but so that's the amortized part.But delete max is slow in unsorted array.I don't know where the maximum is, so I have to scan through the whole array.Uh So, I scan through the array, identify the max is somewhere in the middle.And then if I want to delete it,
if I want to delete that maximum element, well, in a dynamic array, all I can really do is delete the last element efficiently.So, I could, for example, swap it with the last element.So, I take this element and put it here, and then delete the last element in that array, which is pop in Python or delete last in our world.So, overall, this is linear time, which is bad.Uh but I wanted to highlight exactly how it's done for a reason we'll get to in a moment.Sorted array is sort of the reverse.It's very easy to find the max.Where is it?At the end.Delete max, the maximum element is always the last element in a increasing sorted array.Uh I guess that's constant amortized because then I have to delete it, which may incur resizing.Um Insert, though, is going to be linear uh because maybe I can binary search to find where that item where the added item belongs.
Uh let's say I just added this item here.Um I could binary search to find it, but then I'm going to have to do a big shift.So, I might as well just swap repeatedly until I find the position where the added item X belongs.And now I've restored sorted order.That takes linear time.Which is bad.And what we want is somehow the best of these two worlds.Insert is fast for array.Uh Delete is fast for a sorted array.We can't get constant time for both, but we can get log n time for both.We already know how with set AVL trees.But we're going to see a different way to do it today.Uh and the main motivation for a different way to do this is sorting.So I want to define uh priority queue sort.

4. Chapter 4 (8:29)

So given any data structure that implements a priority queue interface, in particular insert and delete max, I can make a sorting algorithm.What do I do?Insert all the items, delete all the items.But because when I delete them, they come out largest first, I get them in reverse sorted order.Then I can reverse in linear time, and I've sorted my items.So we can insert X for X in A or build A and then uh repeatedly delete max.
Okay, how much time does this algorithm take?I'm going to introduce some notation here.It takes however long it takes to build n items.Call that T sub build.Uh n plus uh Sorry.Sorry.plus
times the time to do a delete max.Okay, or we can write this as n times time to do an insert plus time to do a delete max.

5. Chapter 5 (9:58)

Okay, so I'm using these T functions to just abstract uh what are the running times provided by my data structure that implement this interface.Interface says what's correct is and these T functions to give me my performance bounds.So, if I plug in each of these data structures, I get a sorting algorithm.I get AVL sort, I get array sort, I get a sorted array sort.What do those look like?It turns out many of these are familiar.Uh So, uh set AVL's take log n per operation, so we get an n log n sorting algorithm out of them, which is insert all of the items into the AVL tree.I don't want to use AVL build cuz that uses sort.I'm not allowed to sort in order to implement sort.Uh but we saw how to insert into an AVL tree and keep the thing balanced.
Uh so, that takes log n each, and then we can find the max, delete it, rebalance, and so on.Total time will be n log n.This is an algorithm we call AVL sort.It's a bit complicated cuz AVL trees are complicated, but it gives us optimal comparison bound, n log n.Uh Now, um what about array sort?So, suppose I use an unsorted array.I insert the items.So, if I insert the items So, I'm doing all the insertions here before all the deletions.So, what's going to happen is I just insert the items in the original array order.In other words, I just take the array.And then, what I do is repeatedly extract the maximum item uh by searching for it, put moving it to the end of the array, and then repeating that process.Does that sound familiar?That's selection sort from lecture three.
Um so this arrays give us selection sort.

6. Chapter 6 (11:53)

This is a new way to think about what we were doing way back then.Uh with a sorted array, uh what are we doing?We insert all the items.That's actually where all the work happens cuz we maintain the sorted array.So, we start with an empty array, it's sorted.We add an item, okay, still sorted.We add a second item, and we swap if we need to in order to sort.In general, we add an item, we swap it to the left until it's sorted again.That is insertion sort.
Okay, kind of cool.This is a unifying framework for three uh sorting algorithms that we saw before.We didn't actually talk about AVL sort last time, but it was in the notes.And so, that is the right part of this table.So, of course, uh these array data structures are not efficient.They take linear time some for some of the operations, so the sorting algorithms are not efficient.But, they're ones we've seen before, so it's neat to see how they fit in here.Uh they had the selection sort and insertion sort had the advantage that they were in place.You just needed a constant number of pointers or indices uh beyond the array itself.So, they're very space efficient.So, that was a plus for them, but they take n squared time, so you should never use them.Except for like n at most 100 or something.
Um AVL tree sort is great in that it gets n log n time.Probably more complicated than merge sort, and you could stick to merge sort.Uh but neither merge sort nor set AVL tree sort uh are in place.And so, the goal of today is to get the best of all those worlds in sorting to get n log n comparisons, which is optimal in the comparison model, uh but get it to be in place.And that's what we're going to get with binary heaps.Uh we're going to design a data structure that happens to build a little bit faster, as I mentioned, linear time building.Uh so, it's not representing a sorted order in the same way that AVL trees are.Uh but it will be kind of tree-based.It will also be array-based.Uh we're going to get logarithmic time for insert and delete max.
It happens to be amortized cuz we use arrays.Um but when the key thing is that it's an in-place data structure, it only consists of an array of the items.Uh and so, when we plug it into our sorting algorithm, priority queue sort, our generic sorting algorithm, not only do we get nlogen performance, but we also get an in-place sorting algorithm.This will be our first and and only this class, uh nlogen in-place sorting algorithm.Cool.That's the goal.Let's do it.So, uh what we're going to do, uh because we're in place, basically we have to have an array storing our n items.That's sort of the definition of in place, just using n slots of memory, exactly the size of the number of items in our structure.But we're obviously not going to use a regular unsorted array or regular sorted array.Um we're going to use array just as sort of the underlying technology for how things are stored, but we'd really like logarithmic performance, which should make you think tree.
Only way to get a log is with a binary tree, more or less.Um so, tree.Somehow, we want to embed a tree into an array.Let me grab an example.

7. Chapter 7 (15:24)

Let me draw a tree.
If I got to choose any old tree I want, I would choose a tree that's basically perfectly balanced.Perfectly balanced to be like this where uh what's the property that I have all of these levels, all of these depths are completely filled with nodes.This is depth zero.Remember, this is depth one.This is depth two.This is depth three.So, what I'd really like uh is to have uh two to the I nodes at depth I.That would be a perfect binary tree.Uh but that only works when N is one less than a power of two, right?Uh I can't always achieve that for any N.And so, the next best thing I could hope for is uh two to the I nodes at depth I until the very last I, the largest depth.And in that level, I'm still going to restrict things.
I'm going to force all of the nodes to be as far left as possible.Okay.Uh so, I want to say exceptat max depth
uh wherenodes are I'll call them left justified.

8. Chapter 8 (17:10)

And these two properties together uh is what I call a complete binary tree.
Uh why is this interesting?Because I claim I can represent a tree like this as an array.I've narrowed things down enough that I can draw an array down here.Um and what I'm going to do is write these nodes in depth order.So, I write A first cuz that's depth zero, then B C that's depth one, then uh well, they're alphabetical.I made it that way.D E F G is depth two, and then H I J is depth three.Okay, this is very different from traversal order of a tree.Traversal order would have been H D I B J E A F C G.Okay?But, this is what we might call depth order.Do the lowest depth nodes first.Very different way to lay things out or to to linearize our data.Um and this is what a heap is going to look like.
So, the cool thing is between um complete binary trees and arrays is a bijection.For every array, there's a unique complete binary tree.And for every complete binary tree, there's a unique array.Why?Because the complete constraint forces everything.Forces my hand.There's only If I give you a number N, there is one tree shape of size N, right?You just fill in the nodes uh top down until you get to the last level, and then you have to fill them in left to right.What you might call reading order uh for writing down nodes.And the array is telling you which keys go where.This is the first node you write down at the root.This is the next node you write down at the left child of the root, and so on.Okay, so here we have a binary tree represented as an array or array representing a binary tree.
The very specific binary tree.It has a clear advantage, which is it is guaranteed balanced.No rotations necessary in heaps because complete binary trees are always balanced.In fact, they have the best height they possibly could, um, which is ceiling of log n.

9. Chapter 9 (19:39)

Balance remember just meant you were big O of log n.This is 1 * log n, so it's the best um, level of balance you could hope for.So, somehow I claim we can maintain a complete binary tree for solving priority queues.This would not be possible if you were trying to solve the whole set interface, and that's kind of the cool thing about heaps is that by just focusing on the subset of the set interface, we can do more.We can maintain this very strong property, and because we have this very strong property, we don't even need to store this tree.We're not going to store left and right pointers and parent pointers.We're just going to store the array.This is what we call an implicit data structure,
which basically means no pointers,just an array
of the n items.

10. Chapter 10 (20:44)

How are we going to get away without storing pointers?I'd still like to treat it like a tree.I'd still like to know the left child of B is D and the right child of B is E.We'll see why in a moment.Uh, well, we can do this with uh, index arithmetic.So, maybe I should add some labels before I get in there.
So, this array naturally has indices, right?This is index zero.This is index one, index two, index three, index four, index five, index six, seven, eight, nine, because there are 10 items, zero through nine.Uh and I can apply those labels up here, too.These are the same nodes.So, zero, one, two.This is just depth order.But once I have this labeling, it's going to be a lot easier to figure things out.So, if I wanted to know the left child of B is D, somehow given the number one, I want to compute the number three.Uh add two.There are all sorts multiply by three.There are all sorts of operations that take one and turn it into three, but there's only one that's going to work in all cases.And the intuition here is, well, I have two to the I nodes at level I.
If I want to go to the child level, there's two to the I plus one nodes down there, right?Exactly double.Except the very last one, but that won't really matter.If there is a left child, it will behave the same.And so, intuitively, I have this space of size two to the I.I have to expand it to a space of size two to the I plus one, so I should multiply by two.Okay, and that's almost right, but then there's some constants.Uh so, I'd like to say two times I, but if we look at the examples here, one times two is two, which is one less than three.Uh two times two is four, which is one less than five.Hey, we almost got it right.It's just off by one.Off by one is the you know, index errors are the most common things in computer science.
Um What about the right child?If the left child is at two I plus one, where's the right child?I hear lots of mumbles.Two I plus two.One more.Because we're writing things left to right in depth order, the right child is the right sibling of the left child, so it's just one one larger.Okay, given those rules, uh we can also compute parent.It's just whatever is the inverse of both of these functions.Um which I want to divide by two at some point, but be- to get I want to get back to I given 2i + 1 or given 2i + 2, and so um if I subtract one from I,then I either get 2i or 2i + 1, and then if I take an integer division by two, I get I, the original I.Sorry, maybe I'll call this J to be clearer.
So, J is the left or right child, uh then I can reconstruct I, which was the parent.Okay, so this is, you know, constant number arithmetic operations, so I don't have to store left and right pointers.I can just compute them whenever I need them.Whenever I'm at some node like E, uh and I want to know what's its left child, if uh sorry, I given the node index four, which happens to contain the item E, and I want to know what's itsleft child, I just multiply by two and add one, I get nine.Then I can index into this array at position nine, cuz I don't This is just in my head, remember?Uh this is We're just thinking that there's a tree here, but in reality on the computer, there's just the array.So, if we want to go from E to J, we can.
For four to nine, uh if we go try to go to the right child, we multiply by two, eight, add two, 10, and we see, "Oh, 10 is beyond the end of the array," but our array stores itssize, so we realize, "Oh, E does not have a right child."This is something you can only do in a complete binary tree.In a general binary tree, you don't have these nice properties.Cool.Uh so, this is basically a heap.I just need to add one more property,naturally called the heap property.

11. Chapter 11 (25:04)

So, uh There are There are multiple types of heaps.This type of heap is called a binary heap.We will talk about others in future lectures.I'm going to call it Q.Um
Yeah, sure, right.Uh
Let's suppose the thing.This is an array representing a complete binary tree.

12. Chapter 12 (25:48)

Call the array Q.And we want uh every node
to satisfy
uh the so-called max heap property.

13. Chapter 13 (26:16)

Which says Q of I is greater or equal to Q of J uh for both children left of I and right of I.
Okay, so uh We have node I and has two children 2I + 1 and 2I + 2.These are our two values of J.What we want is a greater than or equal to our uh relation here and here.Okay, so this node should be bigger than both this one and this one.Which of these is larger?We don't know, and we don't care.Very different from binary search trees or set binary trees where we said these guys were less than equal to this this one, this one was less than equal to all the nodes in the subtree.Here we're just locally saying this node is greater than equal to this node and this node.So, this is the biggest is at the top.Okay.Um So, one nice lemma about these heaps.This is weird.Um let me give you some more intuition.If you are a binary heap, if you satisfy this max heap property everywhere, then in fact you learn that uh every node I is greater than or equal to all nodes in its subtree.
These are what we call descendants.
Uh and subtree of I.

14. Chapter 14 (28:00)

Okay.Uh let me look at this example.So, I haven't written any numbers here, but you can imagine.Uh so, A here is greater than or equal to both B and C.And B is greater than equal to D and E.And C is greater than equal to F and G.And D is greater than equal to H and I.And E is greater than equal to J.That would make this structure a heap.Not just a complete binary tree.Uh so, what does that imply?It implies that A must be the maximum.So, if you look at any node here like J, A is greater than equal to B is greater than equal to E is greater than equal to J.And in general, what we're saying is that A is greater than equal to all nodes in the tree.B is greater than equal to all nodes in its subtree down here.
C is greater than equal to all nodes in its subtree.That's what this lemma is saying.Um you can prove this lemma by induction, uh, but it's really simple.Um, if you have two nodes I and J and J is somewhere in the subtree, that means there's some downward path from I to J and you know that for every edge we traverse on a downward path, uh,our key is going down non-strictly.Every child is less than or equal to its parent.I is greater than or equal to this is greater than or equal to this is greater than or equal to this is greater than or equal to J.Okay?So, by uh, transitivity of less than or equal to, you know that I is in fact greater than or equal to J.Or, sorry, the key in I is greater than or equal to the key in J.
This is what we're calling I, the index.This is what we would call Q of I.This is index J, Q of J.Okay, very different way to organize, um, keys in a tree.But, as you might imagine, this is going to be good for priority queues cuz priority queues just need to find the maximum element.Okay, then they need to delete it.That's all going to be harder cuz deleting the root is like that's the hardest node to delete intuitively.I'd really prefer to delete leaves.But, deleting leaves and keeping a complete binary tree is actually kind of hard, right?If I want to delete H, that doesn't look like a binary tree or it doesn't look like a complete binary tree anymore.It's not left justified.Uh, if I similarly if I want to delete F, that's bad because now I don't have four nodes here.
The one node that's easy to delete is J.Right?If I remove that node, I still have a complete tree.The last leaf, the last position in my array is the one that's easy to delete.That's good because arrays are good at deleting the last item.But, uh, what I've set up here is it's easy to find the max.It's going to be up here at the root.Deleting it is annoying.I'd like to somehow take that key and put it at position at the last position, at the last leaf, because that's the one that's easy to delete.Okay, and that's indeed what we're going to delete do in a delete algorithm.Uh let me first do insert.I guess that's a little simpler.

15. Chapter 15 (31:05)

Kind of symmetric.
What we just said.So, if I want to insert a key or an item X which has some key, uh again, the only thing I really can do in an array, if I want to add a new item, it has to goat the end.The only thing we know how to do is insert at the end of an array.This is what we called insert last.
This corresponds to adding no- a node containing X uh the item X at the in the very last level of the binary complete binary tree.Either it goes to the right of all the existing nodes or it starts a new level, but it's always going to be the last leaf.After we do the insertion, it will be at position size of Q minus 1.Uh Okay, it This is probably not enough though.We just insert an arbitrary item in a leaf, and now it may not satisfy the max heap property anymore.So, let's just check if it does, and if it doesn't, fix it.That's what we know how to do.Um but this time, we're not even going to need uh

16. Chapter 16 (32:20)

We're not even going to need rotations, which is cool.So, I'm going to define an operation called max heapify up.This will make things more like a max heap.Uh we're going to start at size of Q minus one for a value I, but it's going to be recursive.So, what we're going to do is look at a node I.Uh it's in particular the one that just got inserted, and where could it violate things?Well, with its parent.
Cuz we have no idea what key we just put here.Maybe it's less than our parent, then we're happy.But if it's greater than our parent, we're in trouble, and we should fix it.So, um if
the item in the parent uh its key is less than I's key,uh I see I forgot to write key in all these spots.It should be dot key and dot key.Q of I is an item.Let's guess it's a key.Um so, this is the bad case.This is if the parent is smaller than the child.We wanted the parent to always be greater than or equal to its children.So, in that case, uh what can we do?Swap them.
Let's swap Q parent of I.Excellent, more chalk.Uh and with Q of I.Now, they're in the right order.Okay, now we need to think about what about the other child of that node?And what about its parent?Okay, so um I have some numbers here.Let's say this was five and this was 10.Uh what do I know about this picture before?Well, uh I know that 10 is this newly inserted item.It's the only one that could have caused violations when I first inserted it.So, I know that before this before I move 10 around, I knew all the things in this left subtree are less than or equal to five and everything up here are greater than or equal to five.I also know that the nodes in here in fact were less than or equal to five other than this node 10 that we just inserted.
This was a correct heap.So, five was the separator between things above it on the ancestor chain are are greater than or equal to five and things in its subtree are less than or equal to it.Okay?So, after I do this swap which I'm just going to do.
After I swap the items five and 10, 10 is up here, five is here, and now I realize, okay, great, this edge is happy now 10 is greater than or equal to five, but also this edge is happybecause it used to be happy and we only made its parent larger.Okay?Now, this edge maybe is bad and so we need to recurse.
Recurse on the parent.
But, that's it.Okay?So, we fix this one edge.Initially, this happens way down at the leaf, but in general, we're taking our item that we inserted, which is X, and it starts at the last leaf and it maybe bubbles up for a while.Maybe it gets all the way to the root if we inserted a new maximum item.But, in each step it goes up one and so the running time of of all this stuff is the height of the tree, which is log n.Okay?And because there's only this one item that can potentially be wrong, if it ever stops moving, we've just checked that it satisfies the max heap property.If it gets to the root, you can also check it satisfies the max heap property.So, there's a base case I didn't write here, which is if I equals zero, we're at the root, uh we're done.
Okay?And then you can prove this correct by induction.There's this one item that's in the wrong spot initially, and we put it into a right spot.There are many places it could go, but we will move it to the I guess unique ancestor position that is correct that satisfies max heap property.Okay?So, that's insert.Delete is going to be almost the same.

17. Chapter 17 (37:01)

Delete min, that is.
Sorry, delete max.Thank you.You can, of course, define all of these things for min instead of max.Everything works the same.I just have a hard time remembering which one we're doing.Um just don't switch.You can't use a max heap to do delete min.You can't use a min heap to do delete max, but uh you can use a min heap to do delete min.That's fine.Uh so, like I said, the only lea- the only uh node we really know how to delete is the last leaf in the last level, which is the end of the array, cuz that's what arrays can delete efficiently.And what we what we need to delete is the root item, because that's always the maximum one, which is at the first position in the array.So, what do we do?Swap them.Our usual trick.Um And the cool thing about heaps is we never have to do rotations.
We're only going to do swaps, which is something we had to do with trees also, binary trees.Uh It's like Q of zero with Q of the last item.Great, done.Now we have the last item is the one we want to delete, so we do delete last or pop in Python.And boom, we've got we've now deleted the maximum item.Of course, we may have also messed up the max heap property just like we did with insert.So, with insert we were adding the last leaf.Uh now, what we're doing is swapping the last leaf with the I'm pointing at the wrong picture.Let me go back to this tree.What we did is swap item J with A.So, the problem is now and then we deleted this node.Uh the problem is now that that root node has maybe a very small key cuz it the key that's here now is whatever was down here, which is very low in the tree, so intuitively that's a small value.
Um this is supposed to be the maximum value and we just put a small value in the root.So, what do we do?Heapify down.Uh we're going to take that item and somehow push it down to the tree until the down in the tree until max heap property is satisfied.So, this is going to be max heapify down and we will start at position zero, which is the root.Uh and max heapify down
is going to be recursive algorithm, so we'll start at some position I, but initially that's the root.And what we're going to do is look at position I and its two children.So, let's say we put a very small value up here like zero and let's say we have our children five and 10.We don't know, maybe I'll swap their order just to be more generic cuz that looks like well, not quite a binary search tree, but we don't know their relative order, but one of them is greater than or equalto the other.They're in some order.Um and so, what would I like to do to fix this local picture?
Yeah, I want to swap.And I could swap.Zero is clearly in the wrong spot.It needs to go lower in the tree.I can swap zero with five or zero with 10.Which one?10.I can draw the picture with five, but uh it will not be happy.Um Why 10?We want to do it with the larger one because then this edge will be happy.And also this edge will be happy.If I swapped five up there instead, the five 10 edge would be unhappy.I wouldn't satisfy the max heap property.So, I can do one swap and fix max heap property, except that again zero may be unhappy with its children.Zero is this one item that was in the wrong spot.And so, it may need to go farther down.But five will be Five didn't even move.So, it's happy.
Everything in this subtree is good.Uh what about the parent?Well, if you think about it, because everything was correct a correct heap before we added zero or before we put zero too high, all of these nodes will be greater than or equal to 10.And so, on the ancestor path, um and all of these nodes were less than or equal to 10 before and less than or equal to five.So, that's still true.But you see this tree is happy.Um this tree still may be unhappy.Zero is still might need to push down farther.That's going to be the recursion.Okay, so we check.

18. Chapter 18 (41:56)

I'm here.
Okay, there's a base case, which is if I is a leaf, we're done because there's nothing below them.Uh So uh we satisfy the max-heap property at I cuz there's no children.Um otherwise let's look at the leaf among the left Sorry, left, not leaf.Among the two children left and right of I, right of I might not exist, then ignore it.But uh among the two children that exist, uh find the one that has maximum uh key value.Q of J.keyOkay, that's that was 10 in our example.And then if these items are out of order, if we do not satisfy uh so greater than would be satisfy, uh less than Q of J would be the opposite of the max-heap property here.If If max-heap property is violated, then we fix it by swappingQ of I with Q of J.And then we recurse on J.
Okay, call max-heapify-down of J.That's it.So pretty symmetric.Uh insert was a little bit simpler cuz we only have one parent.Delete min cuz we're pushing down, we have two children, we have to pick one, but there's a clear choice, the bigger one.And again, this algorithm, this whole thing will take order H time, the height of the tree, which is log n.Because our node just sort of bubbles down.At some point it stops.When it stops, we know the max-heap property was satisfied there.And if you check along the way, by induction, all the other max-heap properties will be satisfied cuz they were before.Okay, so almost forced what we could do here.The amazing thing is that you can actually maintain a complete binary tree that satisfies the max-heap property.But once you're told that, the algorithm kind of falls out because we have an array, the only thing we can do is insert and delete the last item.
And so we've got to swap things to there in order to or out of there in order to make that work.Um and then the rest is just checking locally that you can fix fix the property.Cool.Uh So That's almost it.Not quite what we wanted.Uh so we now have log n amortized insert and delete max in our heap.Um we did not yet cover linear builds.Right now it's n log n if you insert n times.And we did not yet cover how to make this an in-place sorting algorithm.So let me sketch each of those.I think first is in-place.Sohow do we make this algorithm in-place?I guess I want that, but I don't need this.So we want to follow priority queue sort.I do want that.

19. Chapter 19 (45:16)

Uh but I don't want to have to uh grow and shrink my array.I would just like to start with the array itself.
So this is in-place.UhSo what we're going to do is say, "Okay, here's my array that I want to sort.That's given to me.That's the input uh to priority queue sort.
And what I'd like is to build a priority queue out of it.Initially, it's empty, and then I want to insert the items one at a time, let's say.Okay, so uh in general, what I'm going to do is maintain that Q is some prefix of A.That's going to be my priority queue.It's going to live in this sub-array, this prefix.Okay, so how do I insert a new item?Well, I just increment.So, to do an insert, the first step is increment size of Q.
Then I will have taken the next item from A and injected it into this queue.And conveniently, if we look at our insert code, which is here, the first thing we wanted to do was add an item at the end of the array.So, we just did it without any actual work, just conceptual work.We just said, "Oh, our queue is one bigger."Boom, now this is at the end of the array.Uh no more amortization, in fact, cuz we're not ever resizing our array.We're just saying, "Oh, now Q is a little bit bigger of a prefix.It just absorbed the next item of A."Similarly, uh delete max
is going to at the end decrement the size of Q.Why is that okay?Because at the end of our delete max operation, not quite at the end, but almost the end, uh we deleted the last item from our array.So, we just replaced that delete last with a decrement, and that's going to shrink the Q by one.And it has the exact same impact as deleting the last item, but now it's constant time worst case, not amortized.And the result is we never actually build a dynamic array, we just use a portion of A to do it.So, what's going to happen is uh we're going to absorb all the items into the priority queue, and then start kicking them out.As we kick them out, we kick out the largest key item first, and we put it here.Then the next largest, then the next largest, and so on.
The minimum item's going to be here, and boom, it's sorted.This is the whole reason I did max heaps instead of min heaps uh is that in the end this will be a a upward sorted array with the max at the end because we always kick out items atthe end and delete the max first.Okay, so that is what's normally called heap sort.You can apply this same trick to insertion sort and selection sort and you actually get the insertion sort and selection sort algorithms that we've seen which operate in prefixes of the array.Okay, cool.So now we have we've achieved the Y up there which is n log n sorting algorithm that is in place.So that was our main goal, heap sort.Let me very quickly mention uh you can build a heap in linear time uh with a clever trick.
So if you insert the items one at a time, that would correspond to inserting down the array and every time I insert an item I have to walk up the tree.So this would be the sum of the depth of each node.If you do that, you get n log n.Okay, this is the sum over I of log I.That turns out to be n log n.It's uh log of n factorial.The cool trick is to instead imagine adding all the items at once and not heapify anything and then heapify up uh sorry, heapify down from the bottom up.So here we're heapifying up.Now we're going to heapify down.And surprisingly that's better because this is the sum of the heights of the nodes.And that turns out to be linear.It's not obvious, but intuitively for a depth this is zero, this is log n.
And we've got a whole ton of leaves.So right at the leaf level, you can see we're paying n log n.Right?Because there are n of them and each one costs log n.Down here, at the leaf level, we're paying constant because um the height of the leaves are one.Here, the height of the root is log n.And this is this is better.Now, we're paying uh a small amount for the thing that of which there are many.And it's not quite a geometric series, but it turns out this is linear.So, that's how you can do linear building heap.To come back to your question about sequence AVL trees, turns out you can get all of the same bounds as heaps except for the in-place part by taking a sequence AVL tree, storing the items in an arbitrary order,and augmenting by max, which is a crazy idea.
Uh but it also gives you linear build time.And yeah, there's other fun stuff in your notes, but I'll stop there.