I am trying to create a max heap , the logic is simple , if parent is smaller then one of its childre, swap them. I tried implementing it using
void maxHeapify( int i , int *a , int n ){
int largest = i;
int left = ( i * 2 ) + 1;
int right = ( i * 2 ) + 2;
if( left < n && a[ largest] < a[ left ])
largest = left;
if( right < n && a[ largest ] < a[right])
largest = right;
if( largest != i ){
swap( a[i], a[largest]);
maxHeapify( largest , a, n );
}
}
int main(){
int n;
int * a;
cout << "Number of elements : ";
cin >> n ;
a = new int[n];
for( int i = 0; i < n ; i++){
cin >> a[i];
}
for( int i = n/2 -1 ; i >= 0 ; i-- ){
maxHeapify( i , a, n);
}
for(int i = 0; i < n ; i++){
cout << a[i] << " ";
}
return 0;
}
i am using input
2 7 26 25 19 17 1 90 3 36
the tree shoud look like
90 36 17 25 26 7 1 2 3 19
so array representation should be 90 36 17 25 26 7 1 2 3 19
yet the output of the code is
90 36 26 25 19 17 1 7 3 2
i looked it up and found many same codes in many tutorials. How come the output isnt representation of the tree in array? Did i misunderstood it?
Thanks for explanation
Why do you expect your heap to look in a specific way? There are many ways in which these input numbers can be arranged into a heap. The result you are getting is also a valid heap - each parent is bigger, than its children:
90
36 26
25 19 17 1
7 3 2
Final heap structure will vary based on insertion order and initial structure. In your case, 2 7 26 25 19 17 1 90 3 36
would yield result you expect if you started with empty heap, inserted elements in given order and heapifed after each insertion.
This code will yield result you expect:
std::vector<int> b = {2, 7, 26, 25, 19, 17, 1, 90, 3, 36};
auto it = b.begin();
while (it != b.end())
{
std::make_heap(b.begin(), it+1);
++it;
}
However, what your code does is preinserts all elements into heap, and then arranges it, equivalent to this:
std::vector<int> b = {2, 7, 26, 25, 19, 17, 1, 90, 3, 36};
std::make_heap(b.begin(), b.end());
Both results are equally valid.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.