在数组中查找一个元素,Arrays提供了一个方便查询的方法。Arrays.binarySearch();
测试列子:
public class MainTestArray { public static void main(String args[]){ String[] intArray = new String[]{"a","b","c","d","e","f","g","h","i","j",}; int positon = Arrays.binarySearch(intArray, "d"); System.out.println("position is:"+positon); } }
测试结果:
position is:3
在数组内查询一个元素,我们可以用“二分法”,上述方法其实也是用的二分法。
实现代码:
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;//无符号右移 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 }
详情请查看java源代码实现。Arrays类