I am looking at a heap problem:
We are given a array with the index value in which we need to check if that index value in the array (i.e. the given heap tree) is in the correct position or not. If not then place the element at the correct position and this process is called heapify.
This is the example heap where values are modified:
My code:
//min-heapify
#include<bits/stdc++.h>
using namespace std;
class minHeap{
int *arr;
int size;
int capacity;
public:
minHeap(int c){
size = 0;
capacity = c;
arr = new int[c];
}
int left(int i) { return (2 * i + 1); }
int right(int i) { return (2 * i + 2); }
int parent(int i) { return (i - 1) / 2; }
//insert fun
void insert(int t){
if(size == capacity)
return;
size++;
arr[size-1] = t;
for(int i=size-1;i!=0 && arr[parent(i)] > arr[i];){
swap(arr[i],arr[parent(i)]);
i = parent(i);
}
}
//print array
void print_array(){
for(int i=0;i<size;i++){
cout<<arr[i]<<" ";
}
}
//min-heapify
void minHeapify(int i){
//finding the smallest among lc rc and current node
int lc = left(i); //left chid
int rc = right(i); //left child
int smallest = i;
//if left child exist and smaller then current
if(lc<size && arr[lc] < arr[i]){
smallest = lc;
}
//if right child exist and smaller then current
if(rc<size && arr[rc] < arr[smallest]){
smallest = rc;
}
//
if(smallest!=i){ //
swap(arr[smallest],arr[i]);
minHeapify(smallest);
}
}
//changes the value in array
void edit(int index,int value){
arr[index] = value;
}
//show the value at any index
int show(int index){
return arr[index];
}
};
int main(){
minHeap h(15);
h.insert(40);
h.insert(20);
h.insert(30);
h.insert(35);
h.insert(25);
h.insert(80);
h.insert(32);
h.insert(100);
h.insert(60);
h.insert(70);
cout<<"perfect minHeap-->"<<endl;
h.print_array();
cout<<endl<<endl;
cout<<"value changed (index 0 and 3)-->"<<endl;
h.edit(0,40);
h.edit(3,20);
h.print_array();
cout<<endl<<endl;
cout<<"passing index of 0-->"<<endl;
h.minHeapify(0);
cout<<"function running...\n"<<endl;
cout<<"Final Array after minHeapify-->"<<endl;
h.print_array();
cout<<endl;
cout<<"left of 20 is :-";
int index = h.left(1);
cout<<h.show(index);
return 0;
}
As you can see in my tree diagram and represented in array form, the output should be the same as a perfect minheap: we check the left of 20 to make sure we get 25.
The heap starts at index 0.