[英]quick sort problem
我使用来自C libary的qsort,并且具有数据类型
Element_type **pElement and Element_type is struct typedef element_type {int ,char ....}
例如,我用
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 );
}
但我总是会遇到细分错误。 为什么?
您的比较函数应通过分别返回负值,零或正值来返回是否认为elem1小于,等于或大于elem2。
同样,如果您想对例如Element_Type
的数组进行排序,则可以将void*
Element_Type*
转换为Element_Type*
。 如果要排序的元素是Element_Type*
则可以将void * Element_Type**
为Element_Type**
。
如果要排序的项目类型为Element_Type*
,请确保为每个项目分配内存,然后在调用qsort之前为每个项目初始化内存。
pElement = (Element_type *)malloc(sizeof(Element_type )* iiNewSize);
您应该调用qsort(pElement,...),而不是qsort(* pElement,...)。 帖子顶部的pElement声明不正确。
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);
稍后编辑:给我们一段代码,这样就可以看到更多问题
这是更正比较功能的最简单方法:
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);
}
我看不到第一个代码段,因此不会对您的段错误提出建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.