+ 1

converting an array into min heap

Can anyone help me in converting an array into min heap ai have tried but it is wrong on some cases

4th Aug 2020, 7:33 AM
Dil Muhammad
Dil Muhammad - avatar
9 ответов
+ 2
I am not supposed to provide you with the code but I can give you standard algorithm to do it. 1) If heap is empty place element at root. 2) Add the element to the bottom level of the heap. 3) Compare the added element with its parent; if they are in the correct order, stop. 4) If not, swap the element with its parent and return to the previous step.
4th Aug 2020, 7:44 AM
Arsenic
Arsenic - avatar
+ 2
Thats what you are doing in this algorithm. You will start with an empty tree and will insert a note at every step. Other method will be to construct a tree and then heapify it.
4th Aug 2020, 7:49 AM
Arsenic
Arsenic - avatar
+ 2
Dil Muhammad looks like you have mixed the syntax of C and C++ together. And also your code looks incomplete. Copy paste it in code playground and then share it here.
4th Aug 2020, 8:22 AM
Arsenic
Arsenic - avatar
4th Aug 2020, 8:34 AM
Dil Muhammad
Dil Muhammad - avatar
+ 1
I want to convert an array with N no of elements into min heap, not insertion and deletion in heap
4th Aug 2020, 7:47 AM
Dil Muhammad
Dil Muhammad - avatar
+ 1
I heapify the tree but not giving output on some case
4th Aug 2020, 7:52 AM
Dil Muhammad
Dil Muhammad - avatar
+ 1
Share your code here.
4th Aug 2020, 7:53 AM
Arsenic
Arsenic - avatar
0
include<stdio.h> void main(){ int arrSize; scanf("%d",&arrSize); int arr[arrSize]; for(int i=0;i<arrSize;i++){ scanf("%d",&arr[i]); } minHeap(arr,arrSize); } void minHeap(int arr[],int n){ int noofswaps=0; int l=0; int temp=0; int indexes[n]; int length=n-1; length=(length-1)/2; if(n!=1){ for(int i=0;i<3;i++){ for(int j=length;j>=0;j--){ if((2*j)+2!=n && (arr[(2*j)+2]<arr[j]) && (arr[(2*j)+2]<arr[(2*j)+1])){ temp=arr[(2*j)+2]; arr[(2*j)+2]=arr[j]; arr[j]=temp; noofswaps++; indexes[l]=j; l++; indexes[l]=(2*j)+2; l++; } else if(arr[(2*j)+1]<arr[j]){ temp=arr[(2*j)+1]; arr[(2*j)+1]=arr[j]; arr[j]=temp; noofswaps++; indexes[l]=j; l++; indexes[l]=(2*j)+1; l++; } }
4th Aug 2020, 8:00 AM
Dil Muhammad
Dil Muhammad - avatar
0
Friend Check this is my code
4th Aug 2020, 8:01 AM
Dil Muhammad
Dil Muhammad - avatar