Question

Given a sorted (in ascending order) integer array nums of n elements and a target value,...

Given a sorted (in ascending order) integer array nums of n elements and a target value, write a method to perform a binary search for a target value in nums. If target exists, then return its index, otherwise return -1. Analyze the running time, T(n).

public int search(int[] nums, int target) {

// YOUR CODE GOES HERE

} // end search

0 0
Add a comment Improve this question Transcribed image text
Answer #1
public int search(int[] nums, int target) {
    int low = 0;
    int high = nums.length - 1;
    int mid;
    while (high >= low) {
        mid = (low + high) / 2;
        if (target == nums[mid])
            return mid;
        else if (target > nums[mid])
            low = mid + 1;
        else
            high = mid - 1;
    }
    return - 1;
}
Add a comment
Know the answer?
Add Answer to:
Given a sorted (in ascending order) integer array nums of n elements and a target value,...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT