Re: Can 'qsort' have an advantage over 'std::sort'?
Martin wrote:
Hi.
Let's consider the following realization of Shell sorting:
void shellsort(
void *pBase,
unsigned N,
unsigned Width,
bool (*Pred)(const void*, const void*)
)
{
char *pData = (char *)pBase;
// Using step sequence 1, 4, 13, 40, ..., 3*n+1
unsigned s;
for (s = 1; s < N/6; s = 3*s + 1);
void *pCur = malloc(Width);
for (; s >= 1; s /= 3)
for (unsigned i = s; i < N; ++i)
{
memcpy(pCur, pData + i*Width, Width);
for (unsigned j = i; j >= s &&
Pred(pCur, pData + (j-s)*Width); j -= s)
memcpy(pData + j*Width,
pData + (j-s)*Width, Width);
if (j != i)
memcpy(pData + j*Width, pCur, Width);
}
free(pCur);
}
Yes, I know, it has many drawbacks, among which are:
1) It lacks type checking, so is not type safe;
2) It's not intuitive, works on a lower level, i. e. deals
with memory, rather than with objects;
3) Writing such code is cumbersome and error prone
Will you agree with me, that it also has one significant advantage?
Let's assume we have an array of objects, which contain a pointer
to a large amount of data. Also the project doesn't provide for a
reference counted realization of this objects' class, so the copy
semantics for our objects is simple deep copying of underlying
data. On the other hand I can't resign deep copying, and use
mere copying of inner pointers. It follows, that using 'std::sort'
for sorting our array is extremely wasteful. In my opinion, better
to use ANSI C's 'qsort', which copies only so-called static part of
objects, leaving alone underlying data. Someone can advice to use
'std::sort' on array of pointers, but what I have is an array of
objects, and I can't make signigicant changes to data representation.
No, the ANSI C qsort has no advantages over std::sort. And the fact
that qsort must copy items in order to sort them - and std::sort does
not - is in fact a significant disadvantage for qsort. Why copy items
if it's not necessary, or if there are more efficient techniques
available?
So how does std::sort rearrange items in a container if not by copying
them? The answer is: by swapping them. So the program should simply
implement a reasonably efficient std::swap for the type of contained
item. Doing so will more than make up std::sort's current deficit
vis-?-vis qsort. And the rest of us (as self-respecting C++
programmers) will then all agree to pretend that the qsort idea was
never a serious suggestion. :-)
Greg
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]