快速排序问题

时间:2010-06-11 11:57:15

标签: c qsort

我使用来自C libary的qsort,我有数据类型

Element_type **pElement and Element_type is struct typedef element_type {int ,char ....} 

示例,我用

调用quicksor函数
qsort(*pElement,iCountElement,(size_t)sizeof(Element_type),compare);

和回调函数

static int compare(const void *p1, const void *p2) {
    Element_type  *a1 = (Element_type  *)p1;
    Element_type *a2 =  (Element_type   *)p2;
    return ( (a2)->iServiceId < (a1)->iServiceId );
}

但我总是得到分段错误。为什么呢?

4 个答案:

答案 0 :(得分:3)

您的比较函数应返回elem1是否被认为小于,等于或大于elem2,分别返回负值,零或正值。

此外,如果您要对Element_Type数组进行排序,则可以将void*转换为Element_Type*类型。如果您尝试排序的元素为Element_Type*,那么您可以将void *转换为Element_Type**

如果您要排序的项目类型为Element_Type*,请确保为每个项目分配内存,然后在调用qsort之前为每个项目初始化。

答案 1 :(得分:1)

   pElement = (Element_type *)malloc(sizeof(Element_type )* iiNewSize);

你应该调用qsort(pElement,...),而不是qsort(* pElement,...)。帖子顶部的pElement声明不准确。

答案 2 :(得分:0)

static int compare(const void *p1, const void *p2) {
    Element_type  *a1 = *(Element_type  *)p1;
    Element_type *a2 =  *(Element_type   *)p2;

    if( (a1)->iServiceId < (a2)->iServiceId )
    {
        return -1; // this means that a1 < a2 in your criteria
    }

    if( (a1)->iServiceId == (a2)->iServiceId )
    {
        return 0; // this means that a1 == a2 in your criteria
    }

    return 1; // this means that a1 > a2 in your criteria
}

像这样调用qsort:

qsort(pElement,iCountElement,(size_t)sizeof(Element_type),compare);

LATER EDIT:为我们提供一段代码,以便我们可以看到更多问题,如果是这样的话

答案 3 :(得分:0)

这是纠正比较功能的最简单方法:

 static int compare(const void *p1, const void *p2) {
    Element_type  *a1 = (Element_type  *)p1;
    Element_type *a2 =  (Element_type   *)p2;
-   return ((a2)->iServiceId < (a1)->iServiceId );
+   return (a1->iServiceId) - (a2->iServiceId);
 }

我无法阅读第一个代码段,因此我不会对您的段错误提出建议。

相关问题