java数组中根据元素查找位置 索引

    xiaoxiao2021-04-14  43

    Arrays提供了一个方便查询的方法 :Arrays.binarySearch();

    public static void main(String[] args) { // TODO Auto-generated method stub String[] arrays = new String[]{"a","b","c","d","e","fff","g","h","i","j",}; int positon = Arrays.binarySearch(arrays, "fff"); System.out.println("position is:"+positon); }

    测试结果:

    position is:5 这个方法也是用的二分法实现的:

    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 } 转载:http://blog.csdn.net/mattdong0106/article/details/22676807

    转载请注明原文地址: https://ju.6miu.com/read-670638.html

    最新回复(0)