0

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?

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Thank you so much. Actually I checked the doc, but missed out the first part "index of the search key, if it is contained in the array". I focused on the rest "otherwise, (-(insertion point) - 1)." This is why I was wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.