+ 1
Dividing an array in half
I came across the following code when dividing an array in half in Merge Sort(c# and java): mid = start + (end - start)/2 .I also saw (start + end)/2 which I know is not as good as the former but don't know why. What benefits do these have instead of array.length/2? Why is the first way better than the others?
2 Respuestas
0
Thanks Bartosz Pieszko. That answered part of my question. I found the other part here although I don't know if it applies to c# or java but applies when using pointers in c++:
https://stackoverflow.com/questions/38688028/why-prefer-start-end-start-2-over-start-end-2-when-calculating-the
in summary start +(end-start)/2 doesn't cause and overflow exception. (start + end)/2 does so avoid in c++
+ 2
It's all similar.
Start + (end - start) / 2 =
(2*start + end - start) / 2 =
(start + end) / 2
Array length/2 is not correct because in merge sort we take parts of array to next recursive steps and we want do it efficiently.