简体   繁体   English

Qsort和Comparators奇怪的行为。 C

[英]Qsort and Comparators weird behaviour. C

So, I am using qsort in my C program from C library. 所以,我在C库的C程序中使用qsort。 It works as expected so I decided to play around with comparators. 它按预期工作,所以我决定玩比较器。

Comparator 1 (I use this): 比较器1(我用它):

 int compare (const void * a, const void * b)
{
  if (*(double*)a > *(double*)b) return 1;
  else if (*(double*)a < *(double*)b) return -1;
  else return 0;  
}

Comparator 2: 比较器2:

int comp (const void *a, const void *b)
{
    const double *ia = (const double *)a; // casting pointer types 
    const double *ib = (const double *)b;
    return *ia  - *ib; 
}

The first one works as I want to. 第一个按我想要的方式工作。 The second one is supposed to do the same the first one. 第二个应该是第一个做同样的事情。 I would like to use the second because the program runs a bit faster, but the thing it that it doesn't really sort anything! 我想使用第二个,因为程序运行得快一点,但事实上它并没有真正排序任何东西!

I am pretty sure that I have used comparator #2 on smaller arrays and it worked. 我很确定我在较小的阵列上使用了比较器#2并且它有效。 Unless I am missing something there. 除非我在那里遗漏了什么。

The second one is supposed to do the same the first one. 第二个应该是第一个做同样的事情。

At the first glance it should, but upon closer examination it turns out that it shouldn't. 乍一看它应该是,但仔细检查后发现它不应该。

Consider, for example, comparing 5.3 and 4.9 . 例如,考虑比较5.34.9 It's clear that the first number is greater than the second one; 很明显,第一个数字大于第二个数字; however, subtracting one from the other produces 0.4 , which rounds down to zero on conversion to int , telling qsort that 5.3 and 4.9 are equal to each other. 但是,从另一个中减去一个会产生0.4 ,在转换为int 向下 qsort入为零,告诉qsort 5.34.9彼此相等。

What you want is to apply signum function to the difference of the two arguments. 你想要的是将signum函数应用于两个参数的差异。 Unfortunately, C standard does not define one; 不幸的是,C标准没有定义一个; see this Q&A for several good work-arounds . 几个好的解决方案的问答

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM