Question

Computer Science - Java

Explain the code step by step (in detailed order). Also explain what the program required. Thanks

7 import java.io.File; 8 import java.util.Scanner; 9 import java.util.Arrays; 10 import java.io.FileNotFoundException; 12 public class insertionSort 13 14 public static void insertionSort (double array]) 15 int n -array.length; for (int j-1; j < n; j++) 17 18 19 20 21 double key - array[j]; int i-_1 while ( (i > -1) && ( array [i] > key array [i+1] - array [i]; 23 2 4 25 26 27 public static void main (String[ ] args) throws FileNotFoundException( 28 Scanner in - new Scanner(System.in); 29 String Filename []= new String[] {input_100.txt, input-1000 (1).txt , input-5000.txt ,in 30 double time s []=new double[Filename.length]; 31 for(int n=0; n<Filename length;n++) 32 L 33 Scanner num - new Scanner (new File(Filename[n])); 34 long startTime, endTime,totalTime; 35 int sum - 0 3 6 37 while (num.hasNextDouble()) 38 double x-num.nextDouble(); 39 sum++ 40 41 num.close(); 42 double [ arr new double[sum]; 43 num - new Scanner (new File (Filename[n])); arrayli+1] -key;

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

I am putting comments under everyline to explain what the line/ command means.

CODE :

import java.io.File;
// inluding the File functions
import java.util.Scanner;
// including the Scanner definition
import java.util.Arrays;
// including the array definition
import java.io.FileNotFoundException;
// including the functions for error handling

public class InsertionSort
{
    public static void insertionSort(double array[])
    {
        int n = array.length;
        // declaring the length of the array given
        for(int j = 1; j < n; j++)
        // initialising the for loop for the sorting to begin
        {
            double key = array[j];
            // assigning the value to a variable
            int i = j-1;
            // declaring a variable that will take the index of the previous element
            while( (i > -1) && ( array[i] > key) )
            // declaring a while loop for sorting the array for each index
            {
                array[i+1] = array[i];
                // if the previous element if greater than the next one.. swap them
                i--;
                // decrease the index by one and repeat
            }
            array[i+1] = key;
            // the first element is given the smallest value
        }
    }
  
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        // defining a new scanner for scanning text
        String Filename[] = new String[]{"file1.txt"};
        // saving already known filenames in a variable;
        double times[] = new double [Filename.length];
        // declaring a variable to save the length of the Filename array
        for(int n = 0; n<Filename.length; n++)
        // initialing the loop to be used for different inputs
        {
            Scanner num = new Scanner(new File(Filename[n]));
            // making the program read from a file
            long startTime, endTime, totalTime;
            // declaring variable that will save the time of the code run
            int sum = 0;
            // stores the number of variables in a file
            while(num.hasNextDouble())
            // this loop will run till the input exists in the file
            {
                double x = num.nextDouble();
                // saves the value from the file in a variable
                sum ++;
                // incrementing the value by 1 for each new value in the file
            }
            num.close();
            // closing the scanner
            double [] arr = new double[sum];
            // initialising an array with "sum" elements
            num = new Scanner(new File(Filename[n]));
            // making it read from the file
            for(int i = 0; i<sum; ++i)
            // initialing the loop to read the values from the file to the array
                arr[i] = num.nextDouble();
                // inputting the values from the file to the array
            num.close();
            // closing the Scanner
            startTime = System.nanoTime();
            // saving the time of the system at this instant
            insertionSort(arr);
            // runs the sorting algorithm
            endTime = System.nanoTime();
            // saving the time of the system at this instant
            totalTime = endTime - startTime;
            // finding the exact time taken to run the algorithm
            times[n] = totalTime;
            // saving the values of the runTime of the insertionSort for its correspoding input
            System.out.println("Time take : " + times[n] + "nanosecond to fort file " + Filename[n]);
            // printing out the time
        }
    }
  
}

Explanation of the complete code :

The insertion sort starts from the first index, and keeps pushing the smallest element to its correct place.
It reads in a number ( jth element ) from the array and goes to the starting of the array from its place one element at a time till it finds its correct place( ith element ) and then it puts the value there.

The main function takes in a bunch of filenames with supposedly different inputs/ different number of inputs. It then reads each file, sorts all those elements from by insertionSort and saves the time taken to sort the elements of all the files then shows them to the user. So, we can compare and examine the time taken by insertionSort on different number of inputs.

*************NOTE*************

If there is any doubt or you need more explanation, Please reply in the comments.
If everything is good rate accordingly :)

Add a comment
Know the answer?
Add Answer to:
Computer Science - Java Explain the code step by step (in detailed order). Also explain what...
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
  • Hello this is my java sorting algorithm program i need all of my errors corrected so...

    Hello this is my java sorting algorithm program i need all of my errors corrected so I can run it. thank you!! import java.util.Scanner;    public class SortingAlogs { public static void main(String[]args){ int array [] = {9,11,15,34,1}; Scanner KB = new Scanner(System.in); int ch; while (true) { System.out.println("1 Bubble sort\n2 Insertion sort\n3 Selection sort\n"); ch = KB.nextInt(); if (ch==1)    bubbleSort(array); if (ch==2)    insertion(array); if (ch==3)    Selection(array); if (ch==4) break;    print(array);    System.out.println(); }    }...

  • Help check why the exception exist do some change but be sure to use the printwriter...

    Help check why the exception exist do some change but be sure to use the printwriter and scanner and make the code more readability Input.txt format like this: Joe sam, thd, 9, 4, 20 import java.io.File; import java.io.PrintWriter; import java.io.IOException; import java.io.FileNotFoundException; import java.io.FileWriter; import java.util.Scanner; public class Main1 { private static final Scanner scan = new Scanner(System.in); private static String[] player = new String[622]; private static String DATA = " "; private static int COUNTS = 0; public static...

  • Problem: Use the code I have provided to start writing a program that accepts a large...

    Problem: Use the code I have provided to start writing a program that accepts a large file as input (given to you) and takes all of these numbers and enters them into an array. Once all of the numbers are in your array your job is to sort them. You must use either the insertion or selection sort to accomplish this. Input: Each line of input will be one item to be added to your array. Output: Your output will...

  • In the code shown above are two parts of two different exercises. HOW WE CAN HAVE...

    In the code shown above are two parts of two different exercises. HOW WE CAN HAVE BOTH OF THEM ON THE SAME CLASS BUT SO WE CAN RECALL them threw different methods. Thank you. 1-First exercise import java.util.Scanner; public class first { public static int average(int[] array){    int total = 0;    for(int x: array)        total += x;    return total / array.length;    } public static double average(double[] array){    double total = 0;    for(double x: array)        total += x;    return total /...

  • Get doubles from input file. Output the biggest. Answer the comments throughout the code. import java.io.File;...

    Get doubles from input file. Output the biggest. Answer the comments throughout the code. import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Lab8Num1 { public static void main(String[] args) { //Declaring variable to be used for storing and for output double biggest,temp; //Creating file to read numbers File inFile = new File("lab8.txt"); //Stream to read data from file Scanner fileInput = null; try { fileInput = new Scanner(inFile); } catch (FileNotFoundException ex) { //Logger.getLogger(Lab10.class.getName()).log(Level.SEVERE, null, ex); } //get first number...

  • I'm attempting to convert ch object array to double array public void calculateSalesPrice() { double salePrice[]...

    I'm attempting to convert ch object array to double array public void calculateSalesPrice() { double salePrice[] = new double[ch.length]; int p = 0; for (int i = 0; i < ch.length; i += 3) { p = i + 1; for(int j = 0;j } } error message:items.java:16: error: cannot find symbol for(int j = 0;j ^ symbol: variable length location: class Object items.java:17: error: array required, but Object found salePrice[j] = (double full program import java.io.File; import java.util.Scanner; import...

  • 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...

  • *JAVA Prompt the user for a movie name. Output the three movies that come alphabetically before...

    *JAVA Prompt the user for a movie name. Output the three movies that come alphabetically before the one entered. I need help correcting my code. I'm unsure why I am getting a name, year, and genre in my output. Input: Jericho Output: Similar title finder. Enter a movie name.\n Here are the 3 movies that are listed before the one you entered\n Jeremy Paxman Interviews...\n Jeremy Taylor\n Jeremy Vine Meets...\n Current output: Similar title finder. Enter a movie name.\n Here...

  • 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...

  • 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...

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