Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

binary search - java Arrays.binarySearch fails to find target

String[] sortedArray = new String[]{"Quality", "Name", "Testing", "Package"};   

// Search for the word "cat" 
int index = Arrays.binarySearch(sortedArray, "Quality");  

I always get -3. Problem is in "Name". Why I can not have "Name" in my array? Any idea?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In order to use binarySearch, you will need to sort the array yourself first:

String[] sortedArray = new String[]{"Quality", "Name", "Testing", "Package"};   

java.util.Arrays.sort(sortedArray);

int index = Arrays.binarySearch(sortedArray, "Quality");  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...