Question

In details explain(the idea in pseudocode) and implement (in java) the following problem: Given a target...

In details explain(the idea in pseudocode) and implement (in java) the following problem: Given a target value and a sorted array, assuming no duplicates in that array, if the target is found in the array, return its index. If not, return where it should be inserted(why it should be inserted there). Give a O(log n) time algorithm.

Example: {2,5,8,10}, target=5, returns 1. {2,5,8,10}, target=6, returns 2.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
//Binarysearch.java
import java.util.Scanner;

public class BinarySearch {

    private static int binarySearch(int[] input, int low, int high, int key) {
        int mid;
        if(low<=high){
            mid = (low+high)/2;
            if(input[mid] == key){
                return mid;
            }
            else if(input[mid] < key){
                return binarySearch(input,mid+1,high,key);
            }
            else{
                return binarySearch(input,low,mid-1,key);
            }
        }
        return -1;
    }



    public static void main(String[] args) {
        int arr[] = {2,5,8,10};
        System.out.println(binarySearch(arr,0,arr.length-1,5));

        int arr2[] = {2,5,8,10};
        System.out.println(binarySearch(arr2,0,arr.length-1,6));
    }
}

Add a comment
Know the answer?
Add Answer to:
In details explain(the idea in pseudocode) and implement (in java) the following problem: Given a target...
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