Graph Data Structure Code Implementations
Production-ready Graph Data Structure data structure implementations in C++, Python, Java, and JavaScript on AntInLoop.
Study Graph Data Structure Guide ยท Launch Visualizer
CPP Implementation
#include <vector>
#include <iostream>
using namespace std;
class Heap {
private:
vector<int> heap;
int heapSize;
void heapify(int i) {
// Find left and right child of node at index i
int left = 2 * i + 1;
int right = 2 * i + 2;
int largest = i;
// If left child is larger than root
if (left < heapSize && heap[left] > heap[largest])
largest = left;
// If right child is larger than largest so far
if (right < heapSize && heap[right] > heap[largest])
largest = right;
// If largest is not root
if (largest != i) {
swap(heap[i], heap[largest]);
heapify(largest);
}
}
public:
Heap() : heapSize(0) {}
void insert(int key) {
heapSize++;
heap.push_back(key);
int i = heapSize - 1;
while (i != 0 && heap[(i - 1) / 2] < heap[i]) {
swap(heap[i], heap[(i - 1) / 2]);
i = (i - 1) / 2;
}
}
void remove() {
if (heapSize <= 0)
return;
else if (heapSize == 1) {
heapSize--;
heap.pop_back();
} else {
heap[0] = heap[heapSize - 1];
heap.pop_back();
heapSize--;
heapify(0);
}
}
bool search(int key) {
for (int i = 0; i < heapSize; i++)
if (heap[i] == key)
return true;
return false;
}
int size() {
return heapSize;
}
bool isEmpty() {
return heapSize == 0;
}
};