Transferred from: http://blog.csdn.net/somebodydie/article/details/8229343
- Package com.jaky;
- Import java.util.*;
- Public class Quest {
- /**
- * @param args
- */
- public static void Main (string[] args) {
- //TODO auto-generated method stub
- string[] Colors = {"blue","Red","green","yellow","Orange","Black"};
- Arrays.sort (colors);
- int S2=arrays.binarysearch (colors, "orange");
- int S3=arrays.binarysearch (colors, "Violet");
- System.out.println (s2+"" +s3);
- }
- }
The output is:
3-6
Violet does not exist in the colors array and has been wondering why S3 is equal to-6
See the JDK API before you know:
BinarySearch
BinarySearch (byte[] A, byte key)
-
Use the binary search method to search for the specified byte array to obtain the specified value. The array must be sorted (by method) before this call is made
sort(byte[]) . If no array is ordered, the result is indeterminate. If the array contains more than one element with the specified value, it is not guaranteed which one is found.
-
-
Parameters:
-
a -the array to search
-
key -The value to search for
-
Return:
-
Returns the index of the search key if it is contained in an array, otherwise (-( insertion point )-1). The insertion point is defined as the point at which the key is inserted into the array: the first element index greater than this key, or a.lengthif all elements in the array are smaller than the specified key. Note that this guarantees that if and only if this key is found, the returned value will be >= 0.
-
When the value to search is not found, return (-( insertion point )-1), although do not know how to understand the insertion point, but after repeated testing results show that it seems to be a negative value of the length of the search array.
JAVA Arrays.binarysearch