Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The conditional operator can be used in 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;

Links to JLS:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading