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

PLEASE US THIS TEMPLATE

import java.util.Scanner;
import java.util.ArrayList;

public class Solution {
public int getIndex(int [] nums, int target) {
//Add code below
  
}
//Sample main to run tests
public static void main(String args[]) {
//Custom set variable
/*
* You can set this value to an item within the array
* Set to 0 by default
*/
int target = 0;
/*
*
*/
//Variables
Scanner scnr = new Scanner(System.in);
ArrayList<Integer> arrList = new ArrayList<Integer>();
int [] arr;
Solution test = new Solution();
//Remaining values will be added to the array
while(scnr.hasNext()){
arrList.add(scnr.nextInt());
}
//Instance primitive array to size of ArrayList
arr = new int[arrList.size()];
//Copy elements from ArrayList to primitive array
for(int i = 0; i < arr.length; i++)
arr[i] = arrList.get(i);
//Test values
int out = test.getIndex(arr,target);
System.out.println(out);
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

If you have any doubts, please give me comment...

import java.util.Scanner;

import java.util.ArrayList;

public class Solution {

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

        // Add code below

        int l = 0, r = nums.length-1;

        int m = l + (r - l) / 2;

        while (l <= r) {

            if (nums[m] == target)

                return m;

            else if (nums[m] < target)

                l = m + 1;

            else

                r = m - 1;

            m = l + (r - l) / 2;

        }

        return m;

    }

    // Sample main to run tests

    public static void main(String args[]) {

        // Custom set variable

        /*

         * You can set this value to an item within the array Set to 0 by default

         */

        int target = 3;

        /*

        *

        */

        // Variables

        Scanner scnr = new Scanner(System.in);

        ArrayList<Integer> arrList = new ArrayList<Integer>();

        int[] arr;

        Solution test = new Solution();

        // Remaining values will be added to the array

        while (scnr.hasNext()) {

            arrList.add(scnr.nextInt());

        }

        // Instance primitive array to size of ArrayList

        arr = new int[arrList.size()];

        // Copy elements from ArrayList to primitive array

        for (int i = 0; i < arr.length; i++)

            arr[i] = arrList.get(i);

        // Test values

        int out = test.getIndex(arr, target);

        System.out.println(out);

    }

}

Add a comment
Know the answer?
Add Answer to:
IN JAVA please Given a sorted array and a target value, return the index if the...
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
  • Create a java class that user put two inputs and first input generate n length array...

    Create a java class that user put two inputs and first input generate n length array of randomly generated numbers. and the second input changes that number of multiples in the array into zero. for example, if the user puts 3 and 5 then it generates 34 60 10 and since the second input is 5 then the multiple of 5 eliminates so it generates 34 0 0 here is the main method that I'm going to use class Main...

  • Background An anagram is a word phrase, or name formed by rearranging the letters of another,...

    Background An anagram is a word phrase, or name formed by rearranging the letters of another, such as the word "cinema", formed from 'iceman". Problem Statement Given two strings s and t, write a function to determine ift is an anagram of S. A sample main function is provided so that you may test your code on sample inputs. Inputs can be provided in the box below your code, please format your input as follows: Example input nose soen Requirements...

  • the code needs to be modifed. require a output for the code Java Program to Implement...

    the code needs to be modifed. require a output for the code Java Program to Implement Insertion Sort import java.util.Scanner; /Class InsertionSort * public class Insertion Sort { /Insertion Sort function */ public static void sort( int arr) int N- arr.length; int i, j, temp; for (i-1; i< N; i++) j-i temp arrli; while (j> 0 && temp < arrli-1) arrli]-arrli-1]; j-j-1; } arrlj] temp; /Main method * public static void main(String [] args) { Scanner scan new Scanner( System.in...

  • Write a Java method that will take an array of integers of size n and shift...

    Write a Java method that will take an array of integers of size n and shift right by m places, where n > m. You should read your inputs from a file and write your outputs to another file. Create at least 3 test cases and report their output. I've created a program to read and write to separate files but i don't know how to store the numbers from the input file into an array and then store the...

  • The code snippet below is an example of pass by reference. We also provide a sample...

    The code snippet below is an example of pass by reference. We also provide a sample method setZeroAt, which sets 0 at a position i in the array, to illustrate pass by reference. public class Sample { public static void setZeroAt(int [] arr, int i){ arr[i] = 0; } public static void main(String[] args) { Scanner input = new Scanner(System.in); int sample[] = {1, 2, 3}; setZeroAt(sample, 1); //Now sample looks like {1, 0, 3} } } Write a Java...

  • JAVA HELP: Directions Write a program that will create an array of random numbers and output...

    JAVA HELP: Directions Write a program that will create an array of random numbers and output the values. Then output the values in the array backwards. Here is my code, I am having a problem with the second method. import java.util.Scanner; import java.util.Random; public class ArrayBackwards { public static void main(String[] args) { genrate(); print(); } public static void generate() { Scanner scanner = new Scanner(System.in);    System.out.println("Seed:"); int seed = scanner.nextInt();    System.out.println("Length"); int length = scanner.nextInt(); Random random...

  • The following code is a Java code for insertion sort. I would like this code to...

    The following code is a Java code for insertion sort. I would like this code to be modified by not allowing more than 10 numbers of integer elements (if the user enters 11 or a higher number, an error should appear) and also finding the range of the elements after sorting. /* * Java Program to Implement Insertion Sort */ import java.util.Scanner; /* Class InsertionSort */ public class InsertionSortTwo { /* Insertion Sort function */ public static void sort( int...

  • I need to write a program in java that reads a text file with a list...

    I need to write a program in java that reads a text file with a list of numbers and sorts them from least to greatest. This is the starter file. import java.util.*; import java.io.*; public class Lab3 { static final int INITIAL_CAPACITY = 5; public static void main( String args[] ) throws Exception { // ALWAYS TEST FOR REQUIRED INPUT FILE NAME ON THE COMMAND LINE if (args.length < 1 ) { System.out.println("\nusage: C:\\> java Lab3 L3input.txt\n"); System.exit(0); } //...

  • I need a java flowchart for the following code: import java.util.*; public class Main {   ...

    I need a java flowchart for the following code: import java.util.*; public class Main {    public static void main(String[] args) {    Scanner sc=new Scanner(System.in);           System.out.print("Enter the input size: ");        int n=sc.nextInt();        int arr[]=new int[n];        System.out.print("Enter the sequence: ");        for(int i=0;i<n;i++)        arr[i]=sc.nextInt();        if(isConsecutiveFour(arr))        {        System.out.print("yes the array contain consecutive number:");        for(int i=0;i<n;i++)        System.out.print(arr[i]+" ");       ...

  • Write and submit the source code for the following program. The program will use an integer...

    Write and submit the source code for the following program. The program will use an integer array of size 10 to store the prices of smartphones. It will then determine and print the prices of the most expensive and cheapest phones. Use the following variables: int[] prices = new int[10]; // Array of smartphone prices Assignment Ask the user for the price of each smartphone (using a for loop) Sort the list of smartphones (once) from low to high price...

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