Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

qsort() vs std::sort, comparison function philosophical difference

Tags:

c++

c

std

I was wondering why there is two entirely different approaches to specify the comparison function in qsort() { C version } vs the std::sort().

qsort needs the comparison function like below: I don't know the reason why it needs three kinds of return values -1 , 0 , +1.

int comp(int *x, int *y){   
   return *x - *y; 
}

while the comparison function for std::sort(), which looks more consistent to me as it is written in terms of function to follows an invariant. i.e if x is smaller than y function return true, x is in the right position relative to y

bool comp(int x, int y){   
       return x < y; 
}

Why do we need three values -1,0,+1 when returning a bool (or int with two value 0 , 1) is much simpler and clean?

like image 293
David Avatar asked Aug 01 '13 18:08

David


People also ask

Why is std :: sort faster than qsort?

STL's sort ran faster than C's qsort, because C++'s templates generate optimized code for a particular data type and a particular comparison function. STL's sort runs 20% to 50% faster than the hand-coded quicksort and 250% to 1000% faster than the C qsort library function.

Why is qsort slower than STD sort?

In general, std::sort is indeed faster than qsort because of a couple of these things: qsort operates on void* , which first requires a dereference, and second requires the size of the data type to perform the swaps.

What is qsort function in C++?

The qsort() function in C++ sorts a given array in ascending order using Quicksort algorithm. The qsort() function uses a comparison function to decide which element is smaller/greater than the other.


1 Answers

Others have pointed out the equivalence of the two ways of doing comparisons; here's why the two approaches are followed.

In C, the comparison needs to be a function pointer. That means you always get function call and pointer indirection overhead. When qsort was designed back in the 1970s on a PDP-11 computer, the amount of overhead had to be reduced so comparison functions such as strcmp did a three-way comparison in a single function call. (Note that qsort is generally an unstable sort, so the equality case may seem useless, but it can be made stable with the appropriate pointer comparisons.)

In C++, the comparison can be inlined at template instantiation time, so much of the overhead is gone (there need not even be a function call) and the simpler convention can be used. This also means that std::sort can work with operator< overloads by default.

like image 53
Fred Foo Avatar answered Sep 28 '22 08:09

Fred Foo