rondo
rondo

Reputation: 63

Best way to sort in descending order

Is it more time-efficient to sort like this:

    sort(ar,ar+n,greater<int>());

or

    bool MyF(int a,int b){ return a>b; }
    sort(ar,ar+n,MyF);

Upvotes: 0

Views: 131

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

Depends on what ar is. If it's a sequence container, the reverse iterators are your friends:

std::sort(ar.rbegin(), ar.rend());

Otherwise, yeah, std::greater<int> seems appropriate for the task...

As for which of your two examples is "better", well, they are functionally equivalent and the former uses a standard library feature that is tested and does the job for you. I see no contest, frankly.

Upvotes: 4

Related Questions