开发者

qsort in c not sorting my array of structs

I'm having an issue with my comparison function for qsort. I've got an array, mGames, of type ListEntry. ListEntry looks like this:

struct ListEntry
{
    bool mLocal;
    int  mLastTurnTime;
};

That's actually rather oversimplified, there's more data in there but it's not being used in the sorting so I omitted it. Anyway, I'm trying to make it so that entries that have mLocal set to true are ordered first. Problem is, I can't get qsort to order my array whatsoever. Here's the comparison function:

int compare(const void* a, const void* b)
{
    ListEntry* e1 = (ListEntry*)a;
    ListEntry* e2 = (ListEntry*)b;
    if (e1->mLocal && e2->mLocal)
        return 0;
开发者_开发问答    return e1->mLocal ? -1 : 1;
}

and my call to it:

qsort(mGames, mNumGames, sizeof(ListEntry), compare);

where mNumGames is the number of games in the array (7 in my current test case), and mGames is defined as:

ListEntry mGames[MAX_GAMES]; // where MAX_GAMES is 50

When I step into the compare method, e1 and e2 contain their data as expected (as in, I'm not accessing garbage memory or didn't dereference things right).

The weird thing is, no matter how I change that comparison method, I can't get the order to change at all. I must be overlooking something really obvious.


Your function is not a partial ordering. This

if (e1.mLocal && e2.mLocal)
    return 0;

should be in fact

if (e1.mLocal == e2.mLocal)

The point is, once you deal with qsort (and other sorting routines as well, you need to ensure the comparison relation is transitive and antisymmetric. That wouldn't be true in your case.

BTW, since you effectively sort only in two classes, it might be faster just to move the elements with .mLocal == 1 to the beginning of the array by something like

ListEntry *first = beginning of the array, *last = end of the array;
while(first < last) {
  if(!first->mLocal && last->mLocal)
    swap(first, last); // swap the two elements
  if(first->mLocal) first++;
  if(!last->mLocal) last --;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜