CSC297.Java, Class 33: Heap Sort and Other Tree Stuff Admin: * How much homework has Alex done? * Will check the assignments and work on it during break. * Review the BST assignment. * No class Wednesday. * Homework: (1) Fix BST so that it incorporates Alex's parent link (2) Implement find (3) Implement delete (4) Finish the heap (deleteSmallest) (5) Write heapSort Overview: * BST * Review of Heaps * Implementing Heaps and Heapsort Review of Binary Search Trees * Trees in which everything smaller is in the left subtree and everything larger is in the right subtree. * Implementation usually based upon variant nodes (contents, left, right). * Key operations: * add: * Check against current location * Greater: Move to the right * Smaller: Move to the left * Stop when you run out of nodes * search/find * Check against current location * Greater: Move to the right * Smaller: Move to the left * Stop when you run out of nodes or find the thing * delete * Find the thing * Replace it with the rightmost value in its left subtree * construct * Do nothing? Heap Review: * A heap is a binary tree that * (a) Is nearly complete * (b) Has the heap property * Nearly complete * Every level but the last is complete (all possible nodes on that level exist) * The final level is "shoved to the left" * Heap property * The value at the root is less than or equal to all values in the left and right subtrees * Both subtrees must be heaps * Observation: * A nearly complete tree of N elements has log_2(N) levels * To find the smallest * It's at the root: O(1) * To delete the smalelst * Shove the righmost thing on the bottom level at the root and swap down * Deleting the root is O(1) * Swapping down is O(log_2N) * Finding the rightmost thing on the bottom level is complicated * To add * Put it at the rightmost place on the bottom level and swap up * Swapping up is O(log_2N) * Finding the righmost place on the bottom level is also complicated * To deal with these complications, we use a cool trick: * Store the heap in a vector * Store "across rows" (first row 0, then row 1, then row 2, then row 3, etc.) * Observe: * If you keep track of the number of things in the heap, you know the array position of the rightmost thing * But how do you then find the left and right children (or the parent) * What is the left child of something at position k? 2k+1 * What is the right child of something at position k? 2k+2 * What is the parent of something at position k? floor((k-1)/2)