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 }