Learner Level

Implement the binarySearchPosition method that returns the index of the target using binary search.

The input contains a sorted integer array nums, its length size, and an integer target. Your task is to return the index of target using binary search.

If the target exists in the array, return its index. If it does not exist, return -1. For example, in [1,3,5,7,9], the target 7 is at index 3.

Example 1

Input
nums (int[]) = [1,3,5,7,9]
size (int) = 5
target (int) = 7
Returns (int) 3

Example 2

Input
nums (int[]) = [2,4,6]
size (int) = 3
target (int) = 5
Returns (int) -1

Example 3

Input
nums (int[]) = [10]
size (int) = 1
target (int) = 10
Returns (int) 0

Binary search works by repeatedly cutting the search range in half.

Keep two pointers, left and right. Check the middle element. If it is equal to the target, return the middle index. If the middle value is smaller, search the right half. Otherwise, search the left half.

Pseudocode:

function binarySearchPosition(nums, size, target):
    left = 0
    right = size - 1
    while left <= right:
        mid = left + (right - left) / 2
        if nums[mid] == target:
            return mid
        else if nums[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.