Answered! I appreciate any help with the following Java problem, please only use Java format for the program….

I appreciate any help with the following Java problem, please only use Java format for the program.

Consider an array data of n numerical values in sorted order and a list of two numerical target values. Your goal is to compute the smallest range of array indices that contains both of the target values. If a target value is smaller than data[0], the range should start with a -1. If a target value is larger than data[n-1], the range should end with n.

For example, given the array

The following table illustrates target values and their corresponding ranges:

— Devise and implement an algorithm that solves this problem —

Expert Answer

 public class ArrayIndex

{
public void smallestRange(int[] arr, int tar1, int tar2)
{
int flag=1,flag1=1;
if(tar1 < arr[0])            // if tar1 is less than first index then set it as -1
tar1 = -1;
if(tar2 > arr[arr.length-1])       // if tar2 value is greater than the max index then set it as 1000
tar2 = 1000;
for(int i=0;i<arr.length;i++)
{
if((tar1!=-1) && (flag==1))
if(tar1 < arr[i+1])
{
tar1 = i;       //set tar1 index if its lower than next element
flag = 0;       //once tar1 is set, it wont allow its operation again
}
if((tar2!=1000) && (flag1==1))
if(tar2 >= arr[i] && tar2 <= arr[i+1])
{
tar2 = i+1;
flag1 = 0;
}

}
if (tar2 == 1000)
tar2 = arr.length;           //if tar2 value is 1000 then set it as arr.length
System.out.println(tar1 + ” ” + tar2);
}
public static void main(String args[])
{
ArrayIndex ai = new ArrayIndex();
int[] arr = {5,8,10,13,15,20,22,26};
int tar1=2, tar2=8;
ai.smallestRange(arr,tar1,tar2);
tar1=9;
tar2=14;
ai.smallestRange(arr,tar1,tar2);
tar1=12;
tar2=21;
ai.smallestRange(arr,tar1,tar2);
tar1=14;
tar2=30;
ai.smallestRange(arr,tar1,tar2);

}
}

Still stressed from student homework?
Get quality assistance from academic writers!