ç的qsort不能正常工作 [英] C qsort not working correctly
问题描述
我不知道我做错了,但下面code没有数组排序正确
I don't know what I'm doing wrong but the following code does not sort the array properly.
#include <stdio.h>
#include <stdlib.h>
int compare(const void* a, const void* b)
{
return (*(int*)a - *(int*)b);
}
int main()
{
int x[] = { -919238029,
-889150029,
-826670576,
-579609061,
-569653113,
-305140505,
-216823425,
-193439331,
-167683147,
-49487019,
-45223520,
271789961,
275570429,
444855014,
559132135,
612312607,
664554739,
677860351,
1005278191,
1031629361,
1089012280,
1115952521,
1521112993,
1530518916,
1907515865,
1931470931,
-1631034645,
-1593702794,
-1465300620,
-1263094822
};
int i;
qsort(x, 30, sizeof(int), compare);
for(i = 0; i < 30; i ++)
printf("%d\n", x[i]);
return 0;
}
产生下面的输出:
produces the following output:
1521112993
1530518916
1907515865
1931470931
-1631034645
-1593702794
-1465300620
-1263094822
-919238029
-889150029
-826670576
-579609061
-569653113
-305140505
-216823425
-193439331
-167683147
-49487019
-45223520
271789961
275570429
444855014
559132135
612312607
664554739
677860351
1005278191
1031629361
1089012280
1115952521
我的意思是,这个问题/必须/是我比较功能。有人注意到有什么奇怪的?
I mean, the problem /must/ be in my compare function. Anybody notice anything strange?
推荐答案
是的,你的比较溢出。 (
Yeah, your "comparison" overflows. :(
当你从一个正数减去一个负数,你的结果不一定是正;如果它不能被重新在数据类型psented $ P $,它会环绕的另一侧。
When you subtract a negative number from a positive number, your result is not necessarily positive; if it can't be represented in the data type, it'll "wrap around" the other side.
如果您的整数只能从-8到7(4位)持有,那么什么时候你比较4到-4?结果发生
那么,你得到8,这是 1000
二进制,这是-8。因此,4小于-4。
If your integer can only hold from -8 to 7 (4 bits), then what happens when you compare 4 to -4?
Well, you get 8, which is 1000
in binary, which is -8. So 4 is less than -4.
不要做减法而不是比较,即使他们告诉你显得多么酷,这是在学校!
Don't do subtraction instead of comparison, even if they tell you "look how cool this is" at school!
这篇关于ç的qsort不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!