here is my code
public class BinarySearch {
public static int binsearch(int key, int[] a)
{
int lo = 0;
int hi = a.length - 1;
while (lo < hi)
{
int mid = (lo + hi) >> 1;
key < a[mid] ? hi = mid : lo = (mid + 1);
}
return lo--;
}
}
i got an error when compiling
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error on tokens, Expression expected instead
Syntax error on token "]", delete this token
Syntax error, insert "]" to complete Expression
and if i change '<' to '>' as
key > a[mid] ? hi = mid : lo = (mid + 1);
got a total different error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error on token ">", -> expected
I am really confused about the ternary operator usage in java. after all, this code works fine in c++
The compiler is having hard time parsing your expression because it is used like a statement-expression.
Since ternary operator is an expression, it should not* be used in place of a statement. Since you would like to control the assignment, which is a statement, with the condition, you should use a regular if:
if (key < a[mid]) {
hi = mid;
} else {
lo = (mid + 1);
)
* In fact, Java does not allow ternary expressions to be used as statements. You could work around this issue by wrapping your expression in an assignment or an initialization (see demo), but this would result in code that is hard to read and understand, so it should be avoided.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With