Question

In: Computer Science

I need to implement incrementalInserstionSort im stuck on that part import java.util.*; /** * This class...

I need to implement incrementalInserstionSort im stuck on that part

import java.util.*;

/**
 * This class represents chains of linked nodes that
 * can be sorted by a Shell sort.
 *
 * @author Charles Hoot
 * @author Frank M. Carrano
 *         Modified by atb
 * @author YOUR NAME
 * @version 9/29/2020
 */
public class ChainSort>
{
    private Node firstNode; // reference to first node

    public ChainSort()
    {
        this.firstNode = null;
    }

    public void display()
    {
        Node currentNode = this.firstNode;
        while (currentNode != null)
        {
            System.out.print(currentNode.data + " ");
            currentNode = currentNode.next;
        }
        System.out.println();
    } // end display

    public boolean isEmpty()
    {
       return this.firstNode == null;
    } // end isEmpty

    public void addToBeginning(T newEntry)
    {
        Node newNode = new Node<>(newEntry);
        newNode.next = this.firstNode;
        this.firstNode = newNode;
    } // end addToBeginning

    public void shellSort(int chainSize)
    {
        //TODO Project3

        for (int space = chainSize / 2; space > 0; space = space / 2)
        {
            //     create sub-chains:
            //          set previousNode to the first node in the chain
            //          set currentNode to the first node in the chain
            //          with a for loop traverse nodes space times using currentNode
            //            to find the second node of the first sub-chain
            //
            //          with a while loop set up backward links for all sub-chains:
            //              set currentNode's previous pointer to the previousNode
            //              set previousNode to its next node and do the same with the currentNode
            Node currentNode = this.firstNode;
            Node previousNode = this.firstNode;
            for (int index = 0; index < space; index++)
            {
                currentNode = currentNode.next;
            }


            while (currentNode != null)
            {
                previousNode = previousNode.next;
                currentNode = currentNode.next;
            }



            System.out.println("\n\u001B[35m\u001B[1m----->Before partial sort with space " + space + " :\u001B[0m");
            display();
            // sort all the sub-chains:
            incrementalInsertionSort(space);
            System.out.println("\u001B[35m\u001B[1m----->After partial sort done with space " + space + " :\u001B[0m");
            display();
        }
    } // end shellSort

    /**
     * Task: Sorts equally spaced elements of a linked chain into
     * ascending order. Sub-chains created with a use of previous.
     *
     * @param space the space between the nodes of the
     *              elements to sort
     */
    private void incrementalInsertionSort( int space)
    {
        //TODO Project3
        // when sorting do not change pointers - simply swap the data if needed


    } // end incrementalInsertionSort


    private class Node
    {
        private S data;
        private Node next;
        private Node previous; // ADDED for linking backwards for shell sort

        private Node(S dataPortion)
        {
            this.data = dataPortion;
            this.next = null;
            this.previous = null;
        }
    } // end Node

    // ************ TEST DRIVER *****************

    public static void main(String args[])
    {
        System.out.println("What size chain should be used?");
        int chainSize = getInt("   It should be an integer value greater than or equal to 1.");

        System.out.println("What seed value should be used?");
        int seed = getInt("   It should be an integer value greater than or equal to 1.");
        Random generator = new Random(seed);
        ChainSort myChain = new ChainSort<>();

        for (int i = 0; i < chainSize; i++)
            myChain.addToBeginning(generator.nextInt(100));

        System.out.print("\nOriginal Chain Content: ");
        myChain.display();
        myChain.shellSort(chainSize);
        System.out.print("\nSorted Chain Content: ");
        myChain.display();
    }


    /**
     * Get an integer value
     *
     * @param rangePrompt String representing a message used to ask the user for input
     * @return an integer
     */
    private static int getInt(String rangePrompt)
    {
        Scanner input;
        int result = 10;        //default value is 10
        try
        {
            input = new Scanner(System.in);
            System.out.println(rangePrompt);
            result = input.nextInt();

        } catch (NumberFormatException e)
        {
            System.out.println("Could not convert input to an integer");
            System.out.println(e.getMessage());
            System.out.println("Will use 10 as the default value");
        } catch (Exception e)
        {
            System.out.println("There was an error with System.in");
            System.out.println(e.getMessage());
            System.out.println("Will use 10 as the default value");
        }
        return result;
    }
} // end ChainSort

Solutions

Expert Solution

Insertion sort is a sorting algorithm in which one element is taken from the unsorted part and is placed in its correct position in the sorted part.

For example:

Let the array be

3 2 4 1 5

First element, 3, is taken and as there is only one element it is sorted and is in correct position. Therefore, the list remains the same.

3 2 4 1 5

Now, 3 is the sorted part and 2 4 1 5 is the unsorted part.

Now, second element, 2, is taken and it is placed in the correct position in the sorted part. Therefore, the list becomes:

2 3 4 1 5

Now, 2 3 is the sorted part and 4 1 5 is the unsorted part.

Now the third element, 4, is taken. The list becomes:

2 3 4 1 5

Now, 2 3 4 is the sorted part and 1 5 is the unsorted part.

Now the fourth element, 1, is taken. The list becomes:

1 2 3 4 5

Finally, the last element is placed.

The final sorted list is:

1 2 3 4 5

Therefore, in this way the list is sorted using the insertion sort algorithm.

Method to sort an array using Insertion sort is as follows:

void sort(int arr[])
{
int n=arr.length;
for (int i=1; i<n; ++i)
{
int key=arr[i];
int j=i-1;
while(j>=0 && arr[j]>key)
{
arr[j+1]=arr[j];
j=j-1;
}
arr[j+1]=key;
}
}


Related Solutions

I need a java flowchart diagram for the following code: import java.util.*; public class Main {...
I need a java flowchart diagram 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]+" ");   ...
Explain the java class below, how it make: import java.util.*; import java.util.concurrent.TimeUnit; public class RacingGame {...
Explain the java class below, how it make: import java.util.*; import java.util.concurrent.TimeUnit; public class RacingGame {       ArrayList<Driver> player = new ArrayList<Driver>();    CarType car = new CarType("Ferrari","2018",280,90,15);    Formula formula = new Formula(5);// number of laps    long startTime = System.currentTimeMillis();    long currentTime = System.currentTimeMillis();    int totalDis = 0;       public static void main(String[] args)    {        RacingGame formulaRace = new RacingGame();        formulaRace.player.add(new Driver("Saleh",10,3));        formulaRace.formula.setDistance(20);//lap distance        formulaRace.totalDis...
import java.util.*; import java.security.*; import javax.crypto.*; import java.nio.file.*; public class CryptoApp {    public static void...
import java.util.*; import java.security.*; import javax.crypto.*; import java.nio.file.*; public class CryptoApp {    public static void main(String[] args) throws Exception { Crypto crypto = new BasicCrypto();        String welcome = "Hello 2043-er's! Let's try this again :-)"; System.out.println(welcome); // First, where are we? //Let's print out our current working directory        Path cwd = FileSystems.getDefault().getPath("").toAbsolutePath(); System.out.println("Current Working Directory: " + cwd); // Read in our file to encrypt    byte[] originalData = Files.readAllBytes(Paths.get(System.getProperty("user.home"), "C-2044-Sample/Crypto/src/encrypt.txt")); // Encrypt it and...
import java.util.*; class A { int i, j, k; public A(int i, int j, int k)...
import java.util.*; class A { int i, j, k; public A(int i, int j, int k) { this.i=i; this.j=j; this.k=k; } public String toString() { return "A("+i+","+j+","+k+")"; } } class Main { public static void main(String[] args) { ArrayList<A> aL=new ArrayList<A>(); Random rand= new Random(1000); //1000 is a seed value for (int p=0; p<10; p++) { int i = rand.nextInt(100); int j = rand.nextInt(200); int k = rand.nextInt(300); aL.add(new A(i, j, k)); } System.out.println("----- Original arraylist------"); for (A a: aL)...
I'm getting an error for this code? it won't compile import java.util.*; import java.io.*; public class...
I'm getting an error for this code? it won't compile import java.util.*; import java.io.*; public class Qup3 implements xxxxxlist {// implements interface    // xxxxxlnk class variables    // head is a pointer to beginning of rlinked list    private node head;    // no. of elements in the list    // private int count; // xxxxxlnk class constructor    Qup3() {        head = null;        count = 0;    } // end Dersop3 class constructor   ...
Im struggling with this clausius clapeyron question and primarily stuck on the second part of the...
Im struggling with this clausius clapeyron question and primarily stuck on the second part of the question, "Calculate the vapor pressure of acetone (b.p. 56.0 °C) at the same column temperature." Calculate the vapor pressure of propanol (b.p. 97.0 °C) at the gas chromatography column temperature of 86.0 °C using the form of the Clausius-Clapeyron equation shown below, p= torr where R is the ideal gas constant, ΔHvap is the enthalpy of vaporization, T1 and T2 are two different temperatures,...
Convert this java code from hashmap into arraylist. import java.io.*; import java.util.*; public class Solution {...
Convert this java code from hashmap into arraylist. import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); HashMap labs = new HashMap(); while (true) { System.out.println("Choose operation : "); System.out.println("1. Create a Lab"); System.out.println("2. Modify a Lab"); System.out.println("3. Delete a Lab"); System.out.println("4. Assign a pc to a Lab"); System.out.println("5. Remove a pc from a Lab"); System.out.println("6. Quit"); int choice = sc.nextInt(); String name=sc.nextLine(); switch (choice) { case 1:...
Add code to the Account class and create a new class called BalanceComparator. import java.util.*; public...
Add code to the Account class and create a new class called BalanceComparator. import java.util.*; public final class Account implements Comparable {     private String firstName;     private String lastName;     private int accountNumber;     private double balance;     private boolean isNewAccount;     public Account(             String firstName,             String lastName,             int accountNumber,             double balance,             boolean isNewAccount     ) {         this.firstName = firstName;         this.lastName = lastName;         this.accountNumber = accountNumber;         this.balance = balance;         this.isNewAccount = isNewAccount;     }     /**      * TO DO: override equals      */     @Override     public boolean equals(Object other) {...
*// 1- Add JavaDoc to This classes 2- Mak a UML */ import java.util.*; public class...
*// 1- Add JavaDoc to This classes 2- Mak a UML */ import java.util.*; public class Display { public static void main(String[] args) { altEnerCar car1 = new altEnerCar(20000, 2001, 20000); altEnerCar car2 = new HydrogenCar(0, 2012, 50000, 100, false); altEnerCar car3 = new ElectricCar(0, 2014, 30000, 10, 50); altEnerCar car4 = new NaturalGasCar(0, 2000, 60000, 5, 20); altEnerCar car5 = new PropaneCar(0, 2011, 45000, 10, true); ArrayList<altEnerCar> cars = new ArrayList<altEnerCar>(); cars.add(car1); cars.add(car2); cars.add(car3); cars.add(car4); cars.add(car5); Collections.sort(cars); System.out.println(cars); }...
I've answered the first half, but im stuck on the second half with multilanes and i...
I've answered the first half, but im stuck on the second half with multilanes and i need help with it . Highway Capacity and Level-of-Service Analysis Freeways A new segment of freeway is being built to connect two existing parallel freeway facilities, in an urban area. The following traffic and roadway characteristics are expected: Traffic Characteristics • AADT = 92000 veh/day • K = 13% • D = 50% • PHF = 0.92 • 8% trucks and buses • 3%...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT