简体   繁体   中英

algorithm of make_heap() function in <algorithm>

I was just experimenting with make_heap() function in C++. Following is the code where I am keeping a track of the elements that are being compared every time the bool predicate() is called, by printing them.

#include <iostream>
#include <algorithm>
using namespace std;

// bool predicate function to make a min heap
bool predicate(int a, int b){
    cout << a << "  " << b << endl;
    if(a >= b){ return 1; }
    return 0;
}


int main(){
    int arr[] = {3,2,1,-1,-2};
    make_heap(arr, arr+5, predicate);
    return 0;
}

The output that I am getting is :
-2 -1
-2 2
1 -2
2 -1
-1 3

But I was expecting the following output, keeping in view the standard algorithm :
-2 -1
-2 2
1 -2
3 -2
2 -1
-1 3

any help ?

I would not say there is an algorithm standardized enough so that you expect specific set of comparisons to be performed. What is standardized is the complexity of the algorithm and as long as the number of comparisons is of linear order you should be good to go. Moreover it seems stl performs better than you in term of number of comparisons so you should not be worried.

As suggested in the comments you can always read the code of the implementation of std::make_heap that your compiler uses but there is no guarantee the same implementation will be used in all implementations of stl .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM