I am very sure that everyone is able to find middle index of array once you know start index and end index of array, but there are certain benefits of using start + (end – start)/2 over (start + end)/2, which are described below :
The very first way of finding middle index is
mid = (start + end)/2
But there is problem with this approach, what if value of start or end or both is INT_MAX, it will cause integer overflow.
The better way of calculating mid index is :
mid = start + (end - start)/2
Let’s try these both methods in C program :
start = 2147483647 end = 2147483647 mid using (start + end)/2 = -1 mid using start + (end - start)/2 = 2147483647
Note : (end – start) may overflow if end < 0 or start < 0
If you see the output, by using second method you get correct output and first method fails to calculate mid and if you use this index (-1 in this case), it can cause segmentation fault because of invalid index of array.
start + (end – start)/2 also works even if you are using pointers :
error: invalid operands of types ‘int*’ and ‘int*’ to binary ‘operator+’ int *mid = (start + end)/2;
It will compile and give expected results
Explanation : pointer addition is not supported in C while pointer subtraction is supported, the reason being the result of subtraction is the difference (in array elements) between the operands. The subtraction expression yields a signed integral result of type ptrdiff_t (defined in the standard include file STDDEF.H)(in short subtraction gives memory distance), but addition of two pointers in not meaningful, that’s why not supported
This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.