+ 6

# Question regarding the mid value used in the most searching and sorting algorithms.

" The safest way to find the middle of two numbers without getting an overflow is as follows: mid = start + (end-start)/2 " Why it can't be mid = (start + end) / 2 ?

11 Answers

+ 9

start + (end - start) / 2
Is preferred because there is a possibility in a very large array that the result from (start + end) could cause an integer overflow where the resulting value is larger than the max value for int. This would end up in a negative value, causing the index to be out of the bounds of the array.

+ 2

Thank You.

+ 2

it is same, m = (l+r)/2
you should know what it does, In array it takes the array indices and then it find the mid value on its basis we access the mid position's value.
let l = start, r = end, m = mid;
m = l + (r-l)/2 = l + r/2 - l/2 = l/2+r/2 = (l+r)/2.
That's how the fancy formula is straight forward written.

+ 1

Use binary sort 😎

+ 1

It is recursive reduction .. that is why..

0

May anyone provide me with an example ?

0

good...to know this thing!!

0

thnx for the help wil try apllying it

0

Hey There!!!
mid = (start + end) / 2 could be done but it is definitely not a recommended way since there could be some cases where starting index i.e [0] and the last index [n] could be very large. Hence, the value of mid in those cases could overshoot the higher constraint. Hence, to deal with such special cases with much more efficiency and no errors, it is recommended to make use of the following equation to calculate mid value:
mid = start + (end-start)/2
Thank You!!
All the Best!!

0

If you've observed, the time complexity of Quicksort is O(n logn) in the best and average case scenarios and O(n^2) in the worst case. But since it has the upper hand in the average cases for most inputs, Quicksort is generally considered the “fastest” sorting algorithm.

Hot today

What's wrong? :(

1 Votes

Why won't my image display

0 Votes

How the answer is 50?

0 Votes

why is this code not working?

2 Votes