End of trees: I finished the destructor Found three bugs: 1. Ordering bug 2. Parent not set in some cases 3. New node might have moved with rebalance Anyway, after that, I think it works Can we use a tree for sorting? Put everything to sort in a tree Do an inorder traversal Running time! How would it be? Analysis. Did we avoid n squared? If so, it should scale ok Let's try it vs. bubble sort We'll just steal pieces from the quicksort demo Note: We didn't do deletion from the tree demo It's really just another round of the same stuff Heaps! "The heap" vs. "A heap": "The heap" is where we obtain dynamically-allocated memory "A heap" is a specialized tree-based data structure They're not related "The heap" is more like "junk heap" or whatnot A heap is NOT a binary search tree! Unlike red-black and AVL The heap property: Children are no greater than their parents Therefore the no node is greater than the root In a max-heap anyway. min-heap is the opposite A heap is a common way to implement a priority queue priority queue: to-do items are sorted by priority Not FIFO or LIFO It's possible to have a non-binary heap, but we'll assume a binary heap Heap operations (Let's add on scaling): find-max O(1) insert O(log(n)) delete-max O(log(n)) search O(n) Why would you want a heap? Schedule writes to a hard drive, or some other device Sorting (heapsort) Anything where you have to deal with an unsorted collection in order Structure property: Each level is completely filled except the last last is filled left to right More strict than AVL Insertion: Insert at leaf Swap with parent until heap property is restored Removing root: Greatest parent replaces root Recursively apply to child's node At leaf, copy last leaf to empty spot and check with parent Implementation: Usually an array, actually! Can you flatten a tree? Don't hurt it! Example Alright: Can we do it? Starting out: Let's take a look at last term's example Did it even work? It wasn't a dynamically-linked data structure Question: Is a sorted array a heap, for that structure? Project 3 will be a heap project