Find locations in Java arrays based on elements __java

Source: Internet
Author: User

A problem today is finding its place in an array based on an element in the array. We know that the binary or the quick lookup method will definitely solve the problem, but I do not want to write a few lines of code (lazy), so I would like to know whether the encapsulation of a good way to solve this problem.

By looking for data, Arrays provides a convenient way to query: Arrays.binarysearch ();

string[] Arrays = new string[]{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J",}; int positon = Arrays.binarysearch (Arrays, "F");
System.out.println ("position is:" +positon);
Test results:

[Java]View Plain Copy position Is:5
In fact, this method is also used by the binary method to achieve:
[Java]  View plain copy public static int binarysearch (Char[] array, int startindex,  int endindex, char value)  {            checkbinarysearchbounds (startindex, endindex, array.length);            int lo = startIndex;           int hi = endIndex - 1;              while  (Lo <= hi)  {                int mid =  (LO  + hi)  >>> 1;//unsigned right shift                 char midVal = array[mid];                   if  (midval < value)  {                    lo = mid + 1;                } else if  (midval >  Value)  {                    hi = mid - 1;                } else {                    return mid;  // value found               }            }           return ~lo;   // value not present       }

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.