Home > OS >  Java ternary operator on simple binary search problem
Java ternary operator on simple binary search problem

Time:01-23

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;
    }
}

CodePudding user response:

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:

CodePudding user response:

Due to my background with primarily JavaScript/TypeScript, I was trying to come up with a solution in Java similar to this:

const binarySearchArr = (arr: number[], target: number): number => {
  let left = 0;
  let right = arr.length - 1;

  while (left <= right) {
    let middle = left   Math.floor((right - left) / 2);

    if (arr[middle] === target) {
      return middle;
    }
    arr[middle] < target ? (left = middle   1) : (right = middle - 1);
  }

  return -1;
};

Per QBrute's comment, the reason I would have to keep "int ans =" is because Java doesn't support using the ternary operator as a standalone expression.

  •  Tags:  
  • Related