• Java中数组Arrays.binarySearch,快速查找数组内元素位置


    在数组中查找一个元素,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类

  • 相关阅读:
    UESTC
    Education Round 8 A
    Gym
    Gym
    hdoj 1159 Common Subsequence
    UVA
    UESTC
    51Nod 1068 Bash游戏 V3 (这规律不好找)
    51Nod 1066 Bash游戏
    51Nod 1002 数塔取数问题
  • 原文地址:https://www.cnblogs.com/jiangu66/p/3162909.html
Copyright © 2020-2023  润新知