Can 'qsort' have an advantage over 'std::sort'?
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.
Waiting for your comments.
Best regards
Martin
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]