Powered by Blogger.

Heap Sort

Heap sort is the one of the most efficient comparison-based algorithms. A sorting algorithm that works by first organizing the data to be sorted into a special type of binary tree called a heap.
A heap is a binary tree that has special structure compared to a general binary tree:
  1. The root is greater than any value in a sub-tree
  • this means the highest priority is at the root
  • this is less information than a BST (Binary Search Tree) and this is why it can be easier and faster
    2.   It is a complete tree
  • the height is always log(n) so all operations are O(log(n))
Balanced binary trees:
 Recall:
  • The depth of a node is its distance from the root 
  • The depth of a tree is the depth of the deepest node 
A binary tree of depth n is balanced if all the nodes at depths 0 through n-2 have two children

  Left-justified binary trees:
A balanced binary tree of depth n is left-justified if:
  • it has 2n nodes at depth n (the tree is “full”), or 
  • it has 2k nodes at depth k, for all k < n, and all the leaves at depth n are as far left as possible 
Plan of attack:
  • First, we will learn how to turn a binary tree into a heap 
  • Next, we will learn how to turn a binary tree back into a heap after it has been changed in a certain way 
Code:


Output: