IN JAVA please
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
Your code will be tested for runtime. Code which does not output a result in logarithmic time (making roughly log(2) N comparisons) will fail the tests.
A sample main function is provided so that you may test your code on sample inputs. For testing purposes, the input must be in sorted order, and a value to insert must be assigned to the target variable in the main function. Inputs can be provided in the box below your code, please format your input as follows:
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 4:
Input: [1,3,5,6], 0
Output: 0
Example 5:
Input: [], 3
Output: 0
import java.io.*;
public class BinarySearch
{
public int binarySearch(int[] objArray, int searchObj)
{
if (objArray == null || objArray.length <= 0)
return 0;
int low = 0;
int high = objArray.length - 1;
int mid = 0;
while (low <= high)
{
mid = (low + high) / 2;
if (objArray[mid] < searchObj)
// compatibility
{
low = mid + 1;
}
else if (objArray[mid] > searchObj)
// compatibility
{
high = mid - 1;
}
else
{
return mid;
}
}
if (objArray[mid] > searchObj)
return mid;
else
return mid + 1;
}
public static void main(String[] args) {
int index;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Integer obj;
try {
BinarySearch bs = new BinarySearch();
int[] intArray = { 1, 3, 5, 6 };
obj = Integer.parseInt("5");
index = bs.binarySearch(intArray, obj);
System.out.println("\nIndex where number: " + obj + " is found or should be inserted = " + index);
int[] intArray2 = { 1,3,5,6 };
obj = Integer.parseInt("2");
index = bs.binarySearch(intArray2, obj);
System.out.println("\nIndex where number: " + obj + " is found or should be inserted = " + index);
int[] intArr3 = { 1,3,5,6 };
obj = Integer.parseInt("7");
index = bs.binarySearch(intArr3, obj);
System.out.println("\nIndex where number: " + obj + " is found or should be inserted = " + index);
int[] intArr4 = { 1,3,5,6 };
obj = Integer.parseInt("0");
index = bs.binarySearch(intArr4, obj);
System.out.println("\nIndex where number: " + obj + " is found or should be inserted = " + index);
int[] intArray3 = { };
obj = Integer.parseInt("3");
index = bs.binarySearch(intArray3, obj);
System.out.println("\nIndex where number: " + obj + " is found or should be inserted = " + index);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
==============================================================================
SEE OUTPUT
Thanks, PLEASE COMMENT if
there is any concern.
Get Answers For Free
Most questions answered within 1 hours.