菜鸟笔记
提升您的技术认知

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

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  
        }