Question

In: Computer Science

I already have the code of this program, I just want to know how to fix...

I already have the code of this program, I just want to know how to fix the code to Implement the 5th function

System.nanotime() and System.currentTimeMillis() methods)

What Code does:

Introduction

Searching is a fundamental operation of computer applications and can be performed using either the inefficient linear search algorithm with a time complexity of O (n) or by using the more efficient binary search algorithm with a time complexity of O (log n).

Task Requirements

In this lab, you will write a Java program to search for an integer in an array using recursive and non-recursive binary search.

Classes:

  1. Binarysearch class

Instance variables

  1. Private data members and Scanner object.
  2. You may choose to include here all instance variables shared by both recursive and non-recursive methods. These may include shared array index and search key variables.

Methods

  1. nonRecursiveBinarySearch (uses iterative/looping construct)

Receives an array of integers and the search key – number to search. If the number is present in the array the method returns its index location and prints the message: ‘number ___ found at index ___’ on the screen. If the number is not found in the array the method returns a sentinel value of -1 and prints the message ‘number _ was not found’.

  1. recursiveBinarySearch (uses recursion)

A method that receives an array of randomly generated integers, the first index and last index of the array, and the number to search. The method then recursively searches for the number entered by the user on the keyboard. Returns the index position if the number is present in the array and prints the message ‘number ___ found at index ___’ on the screen. Returns a sentinel value of -1 if the number is not found and prints the message ‘number __ was not found’.

  1. generateRandomInts

Uses the more SecureRandom class to generate random integers between 10 and 100. Returns an array of random numbers: randomArr, that is, an array that will be populated with 20 randomly generated integer values mainly in the range of 10 to 100 – boundary values excluded i.e. 10

This method prints the sorted array of random integers on the screen.

  1. remainingElements

This method displays elements remaining each time a half of the array is dropped.

  1. System.nanotime() and System.currentTimeMillis() methods

Use these two methods of the System class to determine how long the recursive and non-recursive binary Search operations in (a) and (b) take in nanoseconds and milliseconds. Time taken by each operation should be displayed on the screen. Hint: wrap each method in (a) and (b) with the timing methods.

  1. You may create one more additional method.
  1. Lab3binsearchTest class

Creates a menu as follows:

Select your option in the menu:

  1. Initialize and populate an array of 20 random integers.
  2. Perform a recursive binary search.
  3. Perform a non-recursive binary search.
  4. Exit.

code:

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

class BinarySearch{
        
        // Non recursive binary search
        public int nonRecursiveBinarySearch(int arr[],int target)
        {
                int low=0,high=arr.length-1;
                while(low<=high)
                {
                        remainingElements(arr,low,high);
                        int mid=(low+high)/2;
                        if(arr[mid]==target)
                        {
                                System.out.println("Number "+target +" is found at index "+mid+" :Non recursive binary search");
                                return mid;
                        }
                        else if(arr[mid]<target)
                                low=mid+1;
                        else
                                high=mid-1;
                }
                System.out.println("Number "+target+" was not found   :Non recursive binary search");
                return -1;
        }
        
        // recursive binarySearch
        public int recursiveBinarySearch(int arr[],int first,int last,int target)
        {
                if(first<=last)
                {
                        remainingElements(arr,first,last);
                        int mid=(first+last)/2;
                        if(arr[mid]==target)
                        {
                                System.out.println("Number "+target +" is found at index "+mid+"  : recursive binary search");
                                return mid;
                        }
                        else if(arr[mid]<target)
                                return recursiveBinarySearch(arr,mid+1,last,target);
                        else
                                return recursiveBinarySearch(arr,first,mid-1,target);
                }
                // if not found
                System.out.println("Number "+target +" is not found : recursive binary search");
                return -1;
                
        }
        
        // display method will the array content between two index
        public void remainingElements(int arr[],int l,int r)
        {
                for(int i=l;i<=r;i++)
                        System.out.print(arr[i]+" ");
                System.out.println();
        }
        
        int[] generateRandomInts()
        {
                int arr[]=new int[20];
                Random rand=new Random();
                for(int i=0;i<20;i++)
                        arr[i]=rand.nextInt(89)+11; // generate between 11 to 99
                // sort the array
                Arrays.sort(arr);
                return arr;
        }
        
        public void calculateTime(int arr[],int target)
        {
                // for recusive 
                long start=System.nanoTime();
                recursiveBinarySearch(arr,0,arr.length-1,target);
                long time=System.nanoTime()-start;
                System.out.println("Recursive method will take "+time+"ns");
                
            start=System.currentTimeMillis();
                recursiveBinarySearch(arr,0,arr.length-1,target);
                time=System.currentTimeMillis()-start;
                System.out.println("Recursive method will take "+time+"ms");
                
                
                // for non  recusive 
                          start=System.nanoTime();
                                nonRecursiveBinarySearch(arr,target);
                                 time=System.nanoTime()-start;
                                System.out.println("Non Recursive method will take "+time+"ns");
                                
                            start=System.currentTimeMillis();
                                nonRecursiveBinarySearch(arr,target);
                                time=System.currentTimeMillis()-start;
                                System.out.println("Non Recursive method will take "+time+"ms");
                                
                                
                
        }
        
        
        
}


public class Lab3binarysearchTest {
        

        public static void main(String[] args) {
                
       Scanner sc=new Scanner(System.in);
       BinarySearch bs=new BinarySearch();
       int arr[] = null;
       while(true)
       {
           System.out.println("Select your option int the menu below:\n"
                        + "1.Initialize and populate an array of 20 random integers\n"
                        + "2.Perform a recursive binary search\n"
                        + "3.Perfrom a non-recursive binary search\n"
                        + "4.Exit");
           int choice=sc.nextInt();
           if(choice==1)
           {
                   arr=bs.generateRandomInts();
                   System.out.println("Array of randomly generated integers:");
                   bs.remainingElements(arr, 0, arr.length-1);
                   
           }
           else if(choice==2)
           {
                   System.out.print("Please enter an integer value to search: ");
                int target=sc.nextInt();
                bs.recursiveBinarySearch(arr, 0, arr.length-1, target);
           }
           else if(choice==3)
           {
                   System.out.print("Please enter an integer value to search: ");
               int target=sc.nextInt();
               bs.nonRecursiveBinarySearch(arr, target);
           }
           else if(choice==4)
                   System.exit(0);
           else
                   System.out.println("Enter a valid choice");
           
       }
                
        }

}

Solutions

Expert Solution

If I have understood your problem/doubt correctly, you want to know when and where to call the 5th method and also how to not print the results twice.

I have answered below according to that assumption. If this is not what you want please comment so that I can understand your doubt more properly and try to solve it

You can change the calculateTime function as shown below which is almost same as your code but added a boolean variable 'recursive' to check time for recursive or non-recursive approach. And also, instead of running the same method (either recursive or non-recursive) twice for checking in both nano and milli seconds, we can call the method once and check both times for the exact same function call.

public void calculateTime(int arr[],int target, boolean recusive)
        {
            long startNano, startMilli, timeNano, timeMilli;
            if(!recusive)   // for recusive 
            {
                startNano=System.nanoTime();
                startMilli=System.currentTimeMillis();
                
                recursiveBinarySearch(arr,0, arr.length-1, target);
                
                timeNano=System.nanoTime()-startNano;
                timeMilli=System.currentTimeMillis()-startMilli;
                System.out.println("Recursive method will take "+timeNano+"ns");
                System.out.println("Recursive method will take "+timeMilli+"ms");
                
            }
            else if(recusive)       // for non  recusive 
            {
                startNano=System.nanoTime();
                startMilli=System.currentTimeMillis();
                
                nonRecursiveBinarySearch(arr,target);
                
                timeNano=System.nanoTime()-startNano;
                timeMilli=System.currentTimeMillis()-startMilli;
                System.out.println("Non Recursive method will take "+timeNano+"ns");
                System.out.println("Non Recursive method will take "+timeMilli+"ms");
            }
                
        }

I have also changed the code in main function. The changes are shown below

else if(choice==2)
{
    System.out.print("Please enter an integer value to search: ");
    int target=sc.nextInt();
    bs.calculateTime(arr, target, false);
}
else if(choice==3)
{
   System.out.print("Please enter an integer value to search: ");
   int target=sc.nextInt();
   bs.calculateTime(arr, target, true);
}

Instead of directly calling the recursive and non-recursive methods, we can call the 'calculateTime' method which inturn calls the required methods and notes the time


Related Solutions

Hello I have this error in the code, I do not know how to fix it....
Hello I have this error in the code, I do not know how to fix it. It is written in C++ using a Eclipse IDE Error: libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string bus.h =========== #pragma once #include using namespace std; class Bus { private:    string BusId; // bus ID    string Manufacturer; // manufacturer of the bus    int BusCapacity; // bus capacity    int Mileage; // mileage of bus    char Status; // current status...
I'm getting an error message with this code and I don't know how to fix it...
I'm getting an error message with this code and I don't know how to fix it The ones highlighted give me error message both having to deal Scanner input string being converted to an int. I tried changing the input variable to inputText because the user will input a number and not a character or any words. So what can I do to deal with this import java.util.Scanner; public class Project4 { /** * @param args the command line arguments...
I marked the correct answers to these questions, but I just want to know how to...
I marked the correct answers to these questions, but I just want to know how to solve them. 1) In a cross of AaBbCcDdEeFf X AaBbccDdEeFf, what proportion will have the ABCDeF phenotype? A. 27/64 B. 27/128 C. 27/512 D. 81/512 E. 81/2048 #### 2.) In a cross of two flies +/vg Cy/+ +/se +/ab X +/vg +/+ se/se ab/ab what proportion of the offspring will be mutant in phenotype for all four markers? A. 0 B. 3/64 C. 1/16...
I have the answers listed I just want to know if someone could show me the...
I have the answers listed I just want to know if someone could show me the work step by step! Q1. A ball of mass 60 g is dropped from a height of 3.4 m. It lands on the top of a frictionless ramp at height 1.8 m. The ramp is tilted at an angle of 20 degrees. (a) What is the velocity of the ball at the top of the ramp? Answer: 5.6 m/s (b) At the bottom of...
I want to create an image compression program with matlab use PCA. I have the code...
I want to create an image compression program with matlab use PCA. I have the code listed below. But this code is fail, the image is colorless, but still gray. Can you help me to fix my code. clc clear all picture = im2double(imread('picture1.jpg')); Red = picture(:,:,1); premean = mean(Red(:)); premax = max(Red(:)); premin = min(Red(:)); x = size(Red,1); y = size(Red,2); Z = ones(x,y)*premean; A = (Red - Z)*(1/premax - premin); B = cov(A); [veceig,eig,C] = pcacov(B); NewRed =...
The source code I have is what i'm trying to fix for the assignment at the...
The source code I have is what i'm trying to fix for the assignment at the bottom. Source Code: #include <iostream> #include <cstdlib> #include <ctime> #include <iomanip> using namespace std; const int NUM_ROWS = 10; const int NUM_COLS = 10; // Setting values in a 10 by 10 array of random integers (1 - 100) // Pre: twoDArray has been declared with row and column size of NUM_COLS // Must have constant integer NUM_COLS declared // rowSize must be less...
I already answered the first three questions and put the answer down I just don't know...
I already answered the first three questions and put the answer down I just don't know how to answer the last question which asks to calculate K in the rate law? A clock reaction is run at 20 ºC with several different mixtures of iodide, sodium bromate and acid, to form iodine. Thiosulfate is used to react with the iodine formed initially. Starch indicator is added to form a blue color when all the thiosulfate has been used up and...
I have the solution.. I just do not know how they came up with some of...
I have the solution.. I just do not know how they came up with some of the answers. e.g. sales return and allowande. Exercise 5-11 Calculating income statement components L01,5 Referring to Exhibit 5.15 calculate the missing amounts (round to two decimal places). Company A Company B 2020 2019 2020 2019 Sales     $263,000.00 $187,000.00 ? 114200.00 $48,500.00 Sales Discount $2,630.00 ? 1350.00 $1,200.00 $570.00 Sales Return and Allowance ? 51570 $16,700.00 $6,200.00 ? 2430.00 Net Sales ? 208800.00 $168,950.00...
(Full Program)Write code that shows how deadlocks work. Then write code that shows a fix using...
(Full Program)Write code that shows how deadlocks work. Then write code that shows a fix using semaphores. (Full program)Write code showing the elevator algorithm. c++ Language
So I have written a code for it but i just have a problem with the...
So I have written a code for it but i just have a problem with the output. For the month with the highest temperature and lowest temperature, my code starts at 0 instead of 1. For example if I input that month 1 had a high of 20 and low of -10, and every other month had much warmer weather than that, it should say "The month with the lowest temperature is 1" but instead it says "The month with...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT