Thursday, December 15, 2016

Binary Heaps in C++

Pre-Requisites: What are binary heaps?
See here.

I personally found the implementation given in the above GeeksForGeeks link very long.
The aim of this post is simply to provide a short and efficient implementation of min and max heap in C++.
This helps me to revise just before the placement interviews too. :P

1. Short and efficient code.
2. Works as both max-heap as well as min-heap.

Here is the link of code at ideone.

#include using namespace std; class heap{ vector a; int order; #define l(x) 2*x+1 #define r(x) 2*x+2 #define p(x) (x-1)/2 #define null -INT_MAX public: heap(int x = 0){ order = x; } bool cmp(int x, int y){ if (order == 0) return x>y; //min-heap if (order == 1) return x=n and R>=n) return; int v = (L a{13, 1, 10, 34, 42, -10}; for(int x: a) H.add(x); for(int x: a) cout << H.extract() << " "; return 0; }

No comments:

Post a Comment

Art of Time Management | Achieving Multiple Things in Life

rachit jain blog, Rachit Jain, rachit jain iit roorkee, rachit jain iitr, rachit iitr,rachit codechef, rachit hackerrank, rachit jain micr...