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

Write a program in which you create a 2D array of type double with 30 rows and 1

ID: 3685907 • Letter: W

Question

Write a program in which you create a 2D array of type double with 30 rows and 10 columns. Populate it with random real numbers between 1000 and 2000 and print out the array in tabular format. Next, copy the values into a 1D array and sort the array. Display the median value. Finally, ask the user to enter a search value and output the results of both the linear search and the binary search. The search functions should return the first index that is found. Modify the search functions to allow a tolerance of +/- 1%.

Explanation / Answer

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
  
   public static void main (String[] args) throws java.lang.Exception
   {
       // your code goes here
       double arr[][] = new double[30][10];
       double arr_1D[] = new double[300];  
       int k=0;
       for(int i=0;i<30;i++){
           for(int j=0;j<10;j++){
               Random rn = new Random();
               arr[i][j] = rn.nextInt(2000-1000)+1000;
           }
       }
       for(int i=0;i<30;i++){
           for(int j=0;j<10;j++){
               System.out.println(" "+arr[i][j]);
           }
           System.out.println();
       }
       for(int i=0;i<30;i++){
           for(int j=0;j<10;j++){
               arr_1D[k++] = arr[i][j];
           }
           System.out.println();
       }
       for (int i = 0; i < 300; i++)
{
for (int j = i + 1; j < 300; j++)
{
if (arr_1D[i] > arr_1D[j])
{
double a = arr_1D[i];
arr_1D[i] = arr_1D[j];
arr_1D[j] = a;
}
}
}
System.out.println("Please Enter Key");
Scanner sc = new Scanner(System.in);
double key = sc.nextDouble();
if(binarySearch(arr_1D, key) != -1){
   System.out.println("Index at "+binarySearch(arr_1D,key));
}else{
   System.out.println("Index Not Found");
}
if(linearSearch(arr_1D,key) != -1){
   System.out.println("Index at "+linearSearch(arr_1D,key));
}else{
   System.out.println("Index Not Found");
}
  
  
      
   }
   public static int binarySearch(double [] arr, double key) {

int start = 0;
int end = arr.length - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (key == arr[mid]) {
return mid;
}
if (key < arr[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}
public static int linearSearch(double[] arr, double key) {
for (int index = 0; index < arr.length; index++)
{
if (arr[index] == key)
{
return index;
}
}
return -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