把元素插入有序數組中

折半查找的應用spa

public static void main(String[] args) {
        int[] arr = {4,6,6,7,8,9,10};
        System.out.println(getIndexOf(arr,5));
    }

    public static int getIndexOf(int[] arr, int key){
        int min = 0,
                max = arr.length-1,
                mid;
        while (min<=max){
            mid = (max+min)>>1;
            if ( key > arr[mid])
                min = mid+1;
            else if (key < arr[mid])
                max = mid-1;
            else
                return mid;
        }
        return min;
    }
相關文章
相關標籤/搜索