Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This is java. Consider this binary search algorithm: The Arrays and Collections

ID: 662991 • Letter: T

Question

This is java. Consider this binary search algorithm: The Arrays and Collections classes contain static binarySearch methods that implement the binary search algorithm, but with a useful enhancement. If a value is not found in the array, then the returned value is not, but , where is the position before which the element should be inserted. For example, If no match is found, the search method returns. Modify the method so that if a is not found, the method returns , where s the position before which the element should be inserted. (This is the same behavior as Arrays.binarySearch.)

Explanation / Answer

import java.io.*;
import java.util.Arrays;

public class Solution {
    public int searchInsert(int[] A, int target) {
        int pos = Arrays.binarySearch(A, target);
        if (pos>=0) return pos;
        else return -(pos+1);
    }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote