Find the first element in a sorted array that is greater than the target

后端 未结 8 570
青春惊慌失措
青春惊慌失措 2020-11-30 17:40

In a general binary search, we are looking for a value which appears in the array. Sometimes, however, we need to find the first element which is either greater or less than

8条回答
  •  旧时难觅i
    2020-11-30 18:19

    here is a modified binary search code in JAVA with time complexity O(logn) that :

    • returns index of element to be searched if element is present
    • returns index of next greater element if searched element is not present in array
    • returns -1 if an element greater than the largest element of array is searched
    public static int search(int arr[],int key) {
        int low=0,high=arr.length,mid=-1;
        boolean flag=false;
    
        while(low=arr.length)
                return -1;
            else
            return low;
            //high will give next smaller
        }
    }
    
    public static void main(String args[]) throws IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        //int n=Integer.parseInt(br.readLine());
        int arr[]={12,15,54,221,712};
        int key=71;
        System.out.println(search(arr,key));
        br.close();
    }
    

提交回复
热议问题