Question

IN JAVA please Given a sorted array and a target value, return the index if the...

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

Homework Answers

Answer #1

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.

Know the answer?
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
Similar Questions
using matlab please present code for the following (ALL PARTS PLEASE AND THANK YOU) 1. No...
using matlab please present code for the following (ALL PARTS PLEASE AND THANK YOU) 1. No Input/No Output Write a function that has no input and no outputs. This function will simply display some text when it is called. (this is my code, are there suggestions for improvements?) function Display() disp('some text') end 2. 1 Input/No Outputs Write a function with one input and no outputs. This function will simply display a variable that is provided as an input argument....
Please provide answer in the format that I provided, thank you Write a program that prompts...
Please provide answer in the format that I provided, thank you Write a program that prompts the user to input a string. The program then uses the function substr to remove all the vowels from the string. For example, if str=”There”, then after removing all the vowels, str=”Thr”. After removing all the vowels, output the string. Your program must contain a function to remove all the vowels and a function to determine whether a character is a vowel. You must...
Please post all code in Pseudo code. Please post ORIGINAL answers do not copy from similar...
Please post all code in Pseudo code. Please post ORIGINAL answers do not copy from similar questions. Please post in a format that can be directly copied. Reasoning on answers would be most helpful but not required. Thank you in advance for your help. 1.Design an algorithm to find all the common elements in two sorted lists of numbers. For example, for the lists 2, 5, 5, 5 and 2, 2, 3, 5, 5, 7, the output should be 2,...
You are asked to implement a C++ class to model a sorted array of unsigned integers....
You are asked to implement a C++ class to model a sorted array of unsigned integers. The class is to be used in an embedded application that cannot assume the presence of the STL. The array has to be dynamically allocated in such a way that allows programmers using it to specify the required size. Your class should should: (1) provide the appropriate constructors and destructor; (2) provide methods for updating, and showing numbers in/to the array (e.g., to be...
I have written working code for this problem however it is not producing an output and...
I have written working code for this problem however it is not producing an output and it states is a wrong answer. Please just fix my code below and make it work for the sample test cases and all test cases. You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the...
Java please. Given a sequence of unsorted numbers, determine how badly out of order they are....
Java please. Given a sequence of unsorted numbers, determine how badly out of order they are. Write a program that, for any given sequence of unique natural numbers, will compute the 'distance' between that original ordering and the same set of numbers sorted in ascending order. The distance should be computed by calculating how far displaced each number is in the original ordering from its correct location in the sorted list and summing those results. For instance, given the list...
This is in java and you are not allowed to use Java API classes for queues,...
This is in java and you are not allowed to use Java API classes for queues, stacks, arrays, arraylists and linkedlists. You have to write your own implementations for them. You should construct a BST by inserting node values starting with a null tree. You can re-use the code for the insert method given in the sample code from the textbook. -insert method is provided below Your code should have a menu driven user interface at the command line with...
Instructions Write a Java code Your goal is to take N integer inputs from the user...
Instructions Write a Java code Your goal is to take N integer inputs from the user -- N's value will be given by the user as well. You can assume the user provides a valid value for N, i.e., >0. Store the input integers in an array of size N in the order they are provided. These tasks should be done in the main() method. Create a new method called checkArray() that will take the previously created array as input...
in java pls Write a method that will receive 2 numbers as parameters and will return...
in java pls Write a method that will receive 2 numbers as parameters and will return a string containing the pattern based on those two numbers. Take into consideration that the numbers may not be in the right order. Note that the method will not print the pattern but return the string containing it instead. The main method (already coded) will be printing the string returned by the method. Remember that you can declare an empty string variable and concatenate...
CAN YOU PLEASE WRITE THIS CODE IN A DIFFERENT WAY 'EASIER AND BETTER' QUESTION Using C++...
CAN YOU PLEASE WRITE THIS CODE IN A DIFFERENT WAY 'EASIER AND BETTER' QUESTION Using C++ 11. Write a function that will merge the contents of two sorted (ascending order) arrays of type double values, storing the result in an array out- put parameter (still in ascending order). The function shouldn’t assume that both its input parameter arrays are the same length but can assume First array 04 Second array Result array that one array doesn’t contain two copies of...