JAVA Arrays.binarysearch

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/somebodydie/article/details/8229343

  1. Package com.jaky;
  2. Import java.util.*;
  3. Public class Quest {
  4. /** 
  5. * @param args
  6. */
  7. public static void Main (string[] args) {
  8. //TODO auto-generated method stub
  9. string[] Colors = {"blue","Red","green","yellow","Orange","Black"};
  10. Arrays.sort (colors);
  11. int S2=arrays.binarysearch (colors, "orange");
  12. int S3=arrays.binarysearch (colors, "Violet");
  13. System.out.println (s2+"" +s3);
  14. }
  15. }

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.