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

Arrays.binarySearch not finding the element

I have this piece of code:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        for(int i = 0;i<nums.length;i++){
            int n = target - nums[i];
            int temp = nums[i];
            nums[i] = Integer.MIN_VALUE;

            System.out.println("nums: "+ Arrays.toString(nums));
            System.out.println("n: "+n);
            int result = Arrays.binarySearch(nums,n);
            System.out.println("result: "+result);

            if (result >= 0){
                int[] out = new int[2];
                out[0] = i;
                out[1] = result;
                return out;
            }
            nums[i] = temp;
        }
        return null;
    }
}

Where

int[] nums = {0,3,-3,4,-1};
int target = -1;

The code is supposed to give the output [0,4], but is returning null;
The console output is :

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

nums: [-2147483648, 3, -3, 4, -1]
n: -1
result: -4
nums: [0, -2147483648, -3, 4, -1]
n: -4
result: -1
nums: [0, 3, -2147483648, 4, -1]
n: 2
result: -4
nums: [0, 3, -3, -2147483648, -1]
n: -5
result: -1
nums: [0, 3, -3, 4, -2147483648]
n: 0
result: -4


Why is Arrays.binarySearch() not finding the position of -1?, is it some kind of bug or am I missing something?

>Solution :

From the Javadoc

public static int binarySearch(int[] a, int key) Searches the
specified array of ints for the specified value using the binary
search algorithm. The array must be sorted (as by the sort(int[])
method) prior to making this call. If it is not sorted, the results
are undefined. If the array contains multiple elements with the
specified value, there is no guarantee which one will be found.

It looks to me like your initial array is not already sorted. That means a binary search won’t help you – the best you can do is check every element of the array in turn.

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