Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Revert "Created Application Folder #5" #44

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions Computational_Algorithms/Heaps/heapify.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// an array will be given to you which is not a heap

// heapify function is used to put the given node of bt to its correct position so it follows order of max heap

// for given array we know leaf node are from n/2+1 to n : hence those nodes are alrady a heap individually so we need to solve for 1 to n/2

// if we start indexing from 0 : left =2i+1 right = 2i+2

#include<iostream>
using namespace std;
// O(logn)
void heapify(int *arr , int n, int i){
int leftchild = 2*i;
int rightchild = 2*i +1;
int largest=i;

if(leftchild<n && arr[leftchild]>arr[largest]){
largest=leftchild;
}
else if(rightchild<n && arr[rightchild]>arr[largest]){
largest=rightchild;
}

if(largest!=i){
swap(arr[largest],arr[i]);
heapify(arr,n,largest);
}
}

int main(){
int arr[6]={-1,54,55,53,52,50};
int n=5;
// build heap : O(n)
// if arr started directly from 0th index the i =n/2 -1 where n=arr.size() as leaf node found at arr.size()/2 to arr.size()-1
for(int i=n/2 ; i>0 ;i--){
heapify(arr,n,i);
}

for(int i=1 ; i<=n ;i++){
cout<<arr[i]<<" ";
}
}