Skip to content
Advertisement

Java ternary operator on simple binary search problem

How can I refactor this code to NOT include “int ans =” I’d like to keep the ternary operator. Since int ans is not actually the answer it makes no sense to keep it this way.

What would be the correct way to use the ternary operator to change the left / right values?

public class Main {
    public static void main(String[] args) {

        int[] nums = {-1, 0, 3, 5, 9, 12};
        System.out.println(search(nums, 0));

    }

    public static int search(int[] nums, int target) {
        int middle, left = 0, right = nums.length - 1;
        while (left <= right) {
            middle = left + (right - left) / 2;
            if (nums[middle] == target) return middle;
            int ans = (nums[middle] < target) ? (left = middle + 1) : (right = middle - 1);
        }
        return -1;
    }
}

Advertisement

Answer

The conditional operator can only be used as part of an expression. An expression cannot stand on its own, but needs to be part of a statement. Assigning a variable is a statement. Computing a value and not storing it, is not. Convert the expression to an statement:

int ans = (nums[middle] < target) ? (left = middle + 1) : (right = middle - 1);

Becomes:

if (nums[middle] < target) {
  left = middle + 1;
} else {
  right = middle - 1;
}

If you want to save a few key strokes:

if (nums[middle] < target) left = middle + 1;
else right = middle - 1;

Relevant links to the JLS:

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement