A Beginner’s Guide to Binary Heaps


Heaps are actually very useful for sorting. Using buildHeap(), we can effectively build a heap in \(O(n)\) time, and then we can extract each minimum in the array in \(O(h)\) time. This means that we can extract every element in sorted order in \(O(n\log n)\).

std::vector<Element> sortAscending(std::vector<Element>& v) {
  MinHeap minh;
  while(minh.arr.size() != 0) {

  return minh.arr;

std::vector<Element> sortDescending(std::vector<Element>& v) {
  MaxHeap maxh;
  while(maxh.arr.size() != 0) {

  return maxh.arr;


If you have any questions or concerns, or if I have done something wrong, please leave a comment and let me know!

3 thoughts on “A Beginner’s Guide to Binary Heaps”

  1. I see you don’t monetize devyashis.me, don’t waste
    your traffic, you can earn additional cash every
    month with new monetization method. This is the best adsense alternative for any type of website (they approve all sites),
    for more info simply search in gooogle: murgrabia’s

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.