Quicksorting指向结构的指针数组

时间:2012-11-28 01:19:31

标签: c pointers struct quicksort

我目前正在尝试使用C提供的内置快速排序,以便对指向结构的指针数组进行排序。我想根据结构中的name元素对每个元素进行排序。

虽然每次通过比较函数我的整个数组的调试输出显示该函数确实是移位元素,但最终结果不是正确的排序顺序。有没有我在这里看不到的东西?

typedef struct // The custom data type.
{
    char *name;
} Person;

----------------------------

Person **people; // A dynamically allocated array of Person pointers.
int numPeople;   // The logical index of people.
int maxPeople;   // The current maximum capacity of people.

int compare(const void *a, const void *b) // The comparison function for determining
{                                         //    alphabetic ordering.
   const Person *const *p1 = a;
   const Person *const *p2 = b;
   return strcmp((*p1)->name, (*p2)->name); // Compare alphabetically, return result.
}

void SomeFunction(void)
{
    qsort(people, numPeople, sizeof(Person *), compare); // Perform the sort.
}

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

我已经测试了你的代码,它看起来工作正常。这是我用gcc 4.5.2编译的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct // The custom data type.
{
        char *name;
} Person;

Person **people; // A dynamically allocated array of Person pointers.
int numPeople;   // The logical index of people.
int maxPeople;   // The current maximum capacity of people.

int compare(const void *a, const void *b) // The comparison function for determining
{                                         //    alphabetic ordering.
        const Person *const *p1 = a;
        const Person *const *p2 = b;
        return strcmp((*p1)->name, (*p2)->name); // Compare alphabetically, return result.
}

void SomeFunction(void)
{
        qsort(people, numPeople, sizeof(Person *), compare); // Perform the sort.
}

int main()
{
        int iCnt;

        maxPeople = 4;
        numPeople = 4;

        people = calloc(1, sizeof(Person *) * maxPeople);

        people[0] = calloc(1, sizeof(Person));
        people[1] = calloc(1, sizeof(Person));
        people[2] = calloc(1, sizeof(Person));
        people[3] = calloc(1, sizeof(Person));

        people[0]->name = strdup("Tanya");
        people[1]->name = strdup("Alfred");
        people[2]->name = strdup("Harry");
        people[3]->name = strdup("Oakley");

        for(iCnt = 0; iCnt < numPeople; iCnt ++)
                printf("[%d] %s\n", iCnt, people[iCnt]->name);

        SomeFunction();

        for(iCnt = 0; iCnt < numPeople; iCnt ++)
                printf("[%d] %s\n", iCnt, people[iCnt]->name);

        return 0;
}

代码看起来合法,我不确定是什么问题。您是否可以尝试编译我测试的代码并查看它是否有效?

答案 1 :(得分:0)

你可以试试这个

吗?
int compare(const void *a, const void *b) // The comparison function for determining
{                                         //    alphabetic ordering.
   const Person *p1 = *(const Person**)a;
   const Person *p2 = *(const Person**)b;
   return strcmp((p1)->name, (p2)->name); // Compare alphabetically, return result.
}