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]+" ");   ...
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   ...
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) {...
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,...
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%...
Im not sure how to work part f. I do not need any of the other...
Im not sure how to work part f. I do not need any of the other answers. They're already completed. Can anyone please help with partt F (1-8)? Applying the Central Limit Theorem: The amount of contaminants that are allowed in food products is determined by the FDA (Food and Drug Administration). Common contaminants in cow milk include feces, blood, hormones, and antibiotics. Suppose you work for the FDA and are told that the current amount of somatic cells (common...
In java. Please explain. Consider the following program: } import java.util.*; public class Chapter7Ex12 { static...
In java. Please explain. Consider the following program: } import java.util.*; public class Chapter7Ex12 { static Scanner console = new Scanner(System.in); public static void main(String[] args) { double num1; double num2; System.out.print("Enter two integers: "); num1 = console.nextInt(); num2 = console.nextInt(); System.out.println(); if (num1 != 0 && num2 != 0) System.out.printf("%.2f\n", Math.sqrt(Math.abs(num1 + num2 + 0.0))); else if (num1 != 0) System.out.printf("%.2f\n", Math.floor(num1 + 0.0)); else if (num2 != 0) System.out.printf("%.2f\n",Math.ceil(num2 + 0.0)); else System.out.println(0); }} a. What is the...
I need a pseudocode and UML for this program. import java.util.Random; public class SortandSwapCount {   ...
I need a pseudocode and UML for this program. import java.util.Random; public class SortandSwapCount {    public static void main(String[] args) {        //Generate random array for test and copy that into 3 arrays        int[] arr1=new int[20];        int[] arr2=new int[20];        int[] arr3=new int[20];        int[] arr4=new int[20];        Random rand = new Random();        for (int i = 0; i < arr1.length; i++) {            //Generate random array...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT