moalbait
moalbait

Reputation: 67

I know how to find a midpoint,but in this code i am not sure how will this calculate midpoint if we add to it value

private int mid(int left, int right) {
    if (left <= right)
        return (right - left) / 2 + left;
    else
        return (left - right) / 2 + right;
}

what is the purpose of adding left or right to the result if we are looking for midpoint

Upvotes: 2

Views: 95

Answers (2)

Scott Hunter
Scott Hunter

Reputation: 49893

Another kind of analysis:

mid = (left - right)/2 + right 
    = left/2 - right/2 + right 
    = left/2 + right/2 
    = (left + right)/2

The case where left <= right is left as an exercise.

Upvotes: 1

ostrichofevil
ostrichofevil

Reputation: 734

Let's analyze this code piece by piece:

if (left <= right)

This is if the left value is actually to the left of the right value. If it is, it will treat it as such.

return (right - left) / 2 + left;

(right - left) is the length of the line; divide it by two and you get half the distance. Add that to the left value and you have traveled rightwards for half of the length of the line.

else
    return (left - right) / 2 + right;

This code accounts for the fact that left might actually be greater than right, which means that it is actually on the right. If it is, than the roles of right and left are switched in the next line.

Upvotes: 1

Related Questions