user6490375 - 1 month ago 15

C++ Question

How are the binary predicates evaluated?

For example, if I want to sort in the descending order, then should I write:

`bool isGreater(int x, int y)`

{

return x > y;

}

or

`bool isGreater(int x, int y)`

{

return y > x;

}

What exactly is the difference between the two? I understand that the two parameters would be compared to each other, but what should the return result be -

`true`

`false`

The

`sort()`

`height`

`sort(height, height+N, isGreater);`

Could someone please clarify my doubt? Thanks!

Answer

Here is a very simple ascending order sorting algorithm in psuedo code:

```
for i ← 1 to length(A)-1
j ← i
while j > 0 and A[j-1] > A[j]
swap A[j] and A[j-1]
j ← j - 1
end while
end for
```

Same thing with a predicate "MyCompare(x, y) { return x <= y; }" looks like this:

```
for i ← 1 to length(A)-1
j ← i
while j > 0 and MyCompare(A[j-1], A[j]) == false
swap A[j] and A[j-1]
j ← j - 1
end while
end for
```

Now the sort algorithm can sort in any order just by changing the predicate. Since this predicate is an argument to std::sort that means std::sort can sort in any order.