Question

What are all possible values program can print when run?

import java.util.*;
public class TestClass {         

    static String[] sa = { "a", "aa", "aaa", "aaaa" };     
    static     {         Arrays.sort(sa);     }     

    public static void main(String[] args)     {     
        String search = "";     
        if(args.length != 0) search = args[0];
        System.out.println(Arrays.binarySearch(sa, search));    
    } 
}  

The correct answer is Any number from -5 to 3.

I still don't understand the correct answer.

There are three possibilities.

1) if all elements in the array less than the search key, the insertion point is 4, thus -5 is returned.

2) if all elements in the array greater than the search key, the insertion point is 0, thus -1 is returned.

3) if any element in the array matches the search key, the value returned should range between -5 and -1.

So how can the values from 0 to 3 be returned?

Was it helpful?

Solution

So how can the values from 0 to 3 be returned?

If search = "aaaa" the output will be 3, since that's the position (index) returned by the method binarySearch. Something similiar will happen if:

search = "aaa", output will be 2

search = "aa", output will be 1

search = "a", output will be 0

To understand this, try printing the elements of the array sa:

System.out.println(sa[0]); // index 0
System.out.println(sa[1]); // index 1
System.out.println(sa[2]); // index 2
System.out.println(sa[3]); // index 3

Output:

a
aa
aaa
aaaa

OTHER TIPS

From the javadoc

returns index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key.

You have an array of size 4. Therefore the element can be at indices 0, 1, 2, or 3.

The other possibilities are your points 1 and 2.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top