0

I have a sorted array of numbers with array length as n. For a given item k find index i in the sorted array where elements from index i to n are greater than the given item k. If there is no index present then return -1

This is my program:

public static int getIndex(int[] arr, int k) {
     int x = -1;
     for(int i=0; i<arr.length; i++) {
       if(arr[i] > k) {
           x = i; break;
       }
     }
     return x;
}

The time complexity of this approach is O(n), and I want to reduce it further.

1 Answer 1

1

Since the array is sorted, use binary search for a time complexity of O(log N).

public static int getIndex(int[] arr, int k) {
    int low = 0, high = arr.length - 1;
    while (low <= high) {
        int mid = low + high >>> 1;
        if(arr[mid] > k) high = mid - 1;
        else low = mid + 1;
    }
    return low == arr.length ? -1 : low;
}
Sign up to request clarification or add additional context in comments.

3 Comments

In this line low + high >>> 1 what the 3 arrows indicate, how they work.
@learner It is the same as adding low and high, then dividing by 2, but it avoids overflow issues.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.