我正在测试一些函数的速度,所以我做了一个测试,一次又一次地运行这些函数,并将结果存储在一个数组中。我需要根据我随机生成的数组的大小对它们进行排序。我产生了100个元素。合并排序来拯救!我用的是这个链接让我开始。
我关注的代码部分:
private void mergesort(int low, int high) {
// check if low is smaller then high, if not then the array is sorted
if (low < high) {
// Get the index of the element which is in the middle
int middle = low + (high - low) / 2;
// Sort the left side of the array
mergesort(low, middle);
// Sort the right side of the array
mergesort(middle + 1, high);
// Combine them both
merge(low, middle, high);
}
}它被翻译成VB.NET是
private sub mergesort(low as integer, high as integer)
' check if low is smaller then high, if not then the array is sorted
if (low < high)
' Get the index of the element which is in the middle
dim middle as integer = low + (high - low) / 2
' Sort the left side of the array
mergesort(low, middle)
' Sort the right side of the array
mergesort(middle + 1, high)
' Combine them both
merge(low, middle, high)
end if
end sub更重要的是,对这个问题唯一重要的是
dim middle as integer = low + (high - low) / 2如果你想看看合并排序将如何运行这个宝宝
high low high low
100 0 10 0
50 0 6 4
25 0 5 4
12 0 12 7
6 0 10 7
3 0 8 7
2 0 :stackoverflow error:错误来自于事实7+(8-7)/2= 8。您将看到7和8被传递到mergesort(低、中),然后我们无限循环。现在,在前面的类中,您会再次看到这样的比较。在5和4.4+(5-4)/2=4。因此,从本质上说,对于5和4,它变成4+ (1) /2= 4.5 =4。对于8和7,虽然它是7+ (1) /2= 7.5 =8。
也许我只是使用了错误的实现,或者我的类型设置是错误的,但我的问题是:这难道不是一个危险的标志,表明某些事情与正在发生的四舍五入不对吗?
发布于 2014-08-26 14:38:30
在不了解整个算法的情况下,请注意VB.NET /与C# /不同。默认情况下,后者有整数除法,如果您想要截断VB.NET中的小数位,则必须使用\。
读:操作符
所以我认为这就是你想要的
Dim middle as Int32 = low + (high - low) \ 2发布于 2014-08-26 14:39:39
你的诊断是正确的:有一些与正在发生的四舍五入不一致的东西,但如果你知道在哪里查找,这是完全可以预料的。
来自运算符:
除以两个数字并返回一个浮点结果。
该文档明确指出,如果x和y是整数类型,则x / y返回Double。因此,5 / 2 in VB.NET应该是2.5。
来自运算符:
所有数字类型都有预定义的除法运算符。
再往下看:
当你除以两个整数时,结果总是一个整数。
对于C#,如果x和y是整数,则x / y返回整数(四舍五入)。预计5 / 2 in C#将返回2。
https://stackoverflow.com/questions/25508346
复制相似问题