Insertion sort in java code need output need to print exact. Make sure to give explanation and provide output.My output is printing the wrong comparison. The output it is printing is comarison: 9 and what I need it to output to print the comparisons: 7.

The program has four steps:

Read the size of an integer array, followed by the elements of the array (no duplicates).

Output the array.

Perform an insertion sort on the array.

Output the number of comparisons and swaps performed.

main() performs steps 1 and 2.

Implement step 3 based on the insertion sort algorithm in the book. Modify insertionSort() to:

Count the number of comparisons performed.

Count the number of swaps performed.

Output the array during each iteration of the outside loop.

Complete main() to perform step 4, according to the format shown in the example below.

Hints: In order to count comparisons and swaps, modify the while loop in insertionSort(). Use static variables for comparisons and swaps.

The program provides three helper methods:

// Read and return an array of integers.
// The first integer read is number of integers that follow.
int[] readNums()

// Print the numbers in the array, separated by spaces
// (No space or newline before the first number or after the last.)
void printNums(int[] nums)

// Exchange nums[j] and nums[k].
void swap(int[] nums, int j, int k)


Ex: When the input is:

6 3 2 1 5 9 8


the output is:

3 2 1 5 9 8

2 3 1 5 9 8
1 2 3 5 9 8
1 2 3 5 9 8
1 2 3 5 9 8
1 2 3 5 8 9

comparisons: 7
swaps: 4

Put your java code into the java program,putting in the to do list.

import java.util.Scanner;



public class LabProgram {

// Read and return an array of integers.

// The first integer read is number of integers that follow.

private static int[] readNums() {

Scanner scnr = new Scanner(System.in);

int size = scnr.nextInt(); // Read array size

int[] numbers = new int[size]; // Create array

for (int i = 0; i < size; ++i) { // Read the numbers

numbers[i] = scnr.nextInt();

}

return numbers;

}



// Print the numbers in the array, separated by spaces

// (No space or newline before the first number or after the last.)

private static void printNums(int[] nums) {

for (int i = 0; i < nums.length; ++i) {

System.out.print(nums[i]);

if (i < nums.length - 1) {

System.out.print(" ");

}

}

System.out.println();

}



// Exchange nums[j] and nums[k].

private static void swap(int[] nums, int j, int k) {

int temp = nums[j];

nums[j] = nums[k];

nums[k] = temp;

}



// Sort numbers

/* TODO: Count comparisons and swaps. Output the array at the end of each iteration. */

public static void insertionSort(int[] numbers) {

int i;

int j;



for (i = 1; i < numbers.length; ++i) {

j = i;

// Insert numbers[i] into sorted part,

// stopping once numbers[i] is in correct position

while (j > 0 && numbers[j] < numbers[j - 1]) {

// Swap numbers[j] and numbers[j - 1]

swap(numbers, j, j - 1);

--j;

}

}

}



public static void main(String[] args) {

// Step 1: Read numbers into an array

int[] numbers = readNums();



// Step 2: Output the numbers array

printNums(numbers);

System.out.println();



// Step 3: Sort the numbers array

insertionSort(numbers);

System.out.println();



// step 4

/* TODO: Output the number of comparisons and swaps performed*/

}

}

Answers

Answer 1

The insertion sort algorithm involves sorting an array by individually considering and placing each element.

What is the Insertion sort about?

To apply insertion sort, one should choose an element and then search for its suitable location within the ordered array. The mechanism of Insertion Sort is akin to the way a deck of cards is sorted.

The term insertion order pertains to the sequence of adding components to a data structure, such as a collection such as List, Set, Map, and so on. A List object retains the sequence in which elements are added, but a Set object does not uphold the sequence of the elements when inserted.

Learn more about Insertion sort from

https://brainly.com/question/13326461

#SPJ1

Insertion Sort In Java Code Need Output Need To Print Exact. Make Sure To Give Explanation And Provide
Insertion Sort In Java Code Need Output Need To Print Exact. Make Sure To Give Explanation And Provide

Related Questions

Read floating-point numbers from input until a floating-point number is read that is not in the range -10.0 to 45.0, both exclusive. Then, find the sum of all the floating-point numbers read before the floating-point number that causes reading to stop. Lastly, output the sum, ending with a newline.

Ex: If the input is -9.0 -6.3 -17.5 -3.6 -5.3 -4.3 -8.6, then the output is:

-15.3

Answers

The name "floating point numbers" refers to how the decimal point can "float" to any required location. The binary fraction has value 0/2.

Thus, Because of this, floating point numbers are frequently referred to as "floats" in computer science. In computer science, integers, short, and long numbers are also frequent forms of numbers.

In the same manner that the binary fraction 0.001 has value as 0/2 + 0/4 + 1/8, the decimal fraction 0.125 has value as 1/10 + 2/100 + 5/1000.

The only actual difference between these two fractions is that the first is expressed in base 10 fractional notation and the second in base 2, even though their values are identical. Sadly, the majority of decimal fractions cannot precisely be expressed as binary fractions.

Thus, The name "floating point numbers" refers to how the decimal point can "float" to any required location. The binary fraction has value 0/2.

Learn more about Floating numbers, refer to the link:

https://brainly.com/question/13151971

#SPJ1

In addition to S/MIME, there are several protocols and standards that protect email. These include STARTTLS, DNS-Based Authentication of Named Entities (DANE), Sender Policy Framework (SPF), DomainKeys Identified Mail (DKIM), and Domain-based Message Authentication, Reporting, and Conformance (DMARC). Use the Internet to research each of these. Create a summary of each along with the respective strengths and weaknesses. Which would you recommend? Why?

Answers

SPF and/or DKIM results are the basis for DMARC, thus the email domain must have at least one of them in place.

Thus, You must publish a DMARC entry in the DNS in order to install DMARC. After confirming the status of SPF and DKIM, a DMARC record is a text entry within the DNS record that states the policy for your email domain.

If either SPF, DKIM, or both pass, DMARC authenticates. This is known as identifier alignment or DMARC alignment.

The reporting email address specified in the DMARC record is likewise instructed by a DMARC record to receive XML reports from email servers.

Thus, SPF and/or DKIM results are the basis for DMARC, thus the email domain must have at least one of them in place.

Learn more about DMARC, refer to the link:

https://brainly.com/question/17298886

#SPJ1

State two skills to be used to access information from the internet inorder to avoid unwanted materials

Answers

Answer:

Two skills that can be used to access information from the internet while avoiding unwanted materials namely effective search strategies, critical evaluation of sources.

What is not an option when a user is exporting contacts to share with others?

VCARD files
Electronic business cards
XML
CSV

Answers

An option when a user is exporting contacts to share with others is the VCARD files option

What is VCARD?

VCF, or vCard, is a file format standard for electronic business cards. vCards can be attached to e-mail messages, sent over MMS, the World Wide Web, instant messaging, NFC, or via QR code.

A vCard allows you to communicate contact information in a format that other e-mail systems can readily read. A vCard is saved as a. vcf file, which is the Internet standard for storing and distributing contact information.

Learn more about VCARD files here:

https://brainly.com/question/18240279

#SPJ1

write the pseudocode to input 5 numbers from the keyboard and output the result​

Answers

Answer:

Explanation:

// Initialize variables

total = 0

counter = 1

// Loop to get 5 numbers

while counter <= 5 do

   // Get input from user

   input_number = input("Enter number " + counter + ": ")

   

   // Convert input to a number

   number = parseFloat(input_number)

   

   // Add number to the total

   total = total + number

   

   // Increment counter

   counter = counter + 1

end while

// Calculate the average

average = total / 5

// Output the result

print("The total is: " + total)

print("The average is: " + average)

What was the main subject of Ralph Nader's book, Unsafe at any Speed?
O the importance of political action committees and lobbyists
O the way non-profit organizations can affect governmental policies
O the lack of U.S. automobile manufacturing safety standards
O the way the U.S. government infringes on liberties by implementing safety policies

Answers

The main subject of Ralph Nader's book, Unsafe at any Speed, was the lack of U.S. automobile manufacturing safety standards.

Answer:

the lack of U.S. automobile manufacturing safety standards

Explanation:

While making investments in BI analytics seems like a good idea, FDNY is strongly challenged in
measuring its success. Officials may be able to cite statistics showing a reduction in the number
of fires but demonstrating that BI analytics tools were the reason behind that decrease may be
difficult because it involves proving a negative – that something didn’t happen because of its
efforts. Go to the FDNY citywide statistics Web site at citywide-statistics (nyc.gov). Use those
statistics and a data visualization tool of your choice to see if you can discern any change in the
number of fires since the BI analytics system was installed in 2014. (

Answers

BI tools help reduce fire frequency by increasing public awareness, corrective action, and education.

The FDNY has relied largely on BI statistical methods to predict what structures are going to catch fires since 2014. BI analytical tools present several kinds of reports that can demonstrate how the advent of data mining has significantly aided in the process of reducing the frequency of fires in the New York City area.

This is because BI tools may substantially assist in establishing an average for evaluating programs. Increase public awareness of the crisis. Encourage corrective action. Create a set of priorities. Finally, focus on educational programs.

Learn more about BI tools, here:

https://brainly.com/question/31258434

#SPJ1

11
Select the correct answers from each drop-down menu.
When you right-click over a picture in a word processing program, which actions can you choose to perform on that image
an image when you right-click the picture in the word processing program. You can also
an image when you right-click the picture in the word processing program.
You can choose to
Reset
Next

Answers

You can choose to Rotate an image when you right-click the picture in the word processing program. You can also choose to Resize an image when you right-click the picture in the word processing program.

What is a word processing program?

The act of creating, editing, saving, and printing documents on a computer is referred to as word processing. Word processing requires the use of specialist software (known as a Word Processor).

Microsoft Word is one example of a word processor, although other word-processing tools are also commonly used. Ceasing software. Word allows you to incorporate images into your document, like as company logos, photos, and other images, to add interest or a more professional speed (look) to your document

Learn more about Program on

https://brainly.com/question/11347788

#SPJ1

Given the list primes, ``primes = [2, 3, 5, 7, 11, 13, 17, 19, 23,29]``, How do you obtain the primes 2 and 13? Select one: a. primes[::6] b. primes[::4] c. primes[::5] d. primes[::13]

Answers

Answer:2 and 13 are the prime numbers because of the factors they are having.Factorization of a prime number yields the same number and 1 as its factor.

Explanation:

1.Prime numbers are those numbers when factorize they split into the same number itself and 1.

2.The factorization of 2 is as follows:  x

3.The prime factor of 2 contains 2 itself as well as 1, and therefore it is a prime number.

4.The factorization of 13 is as follows:  ×

5.Therefore, 13 is also prime because of its prime factors.

E

To use the loadtxt command, each row should have the same number of values?

Select one:
True
False

Answers

True is the correct answer

Define a class named Rectangle with a constructor that initializes the length and width with parameters (eLength, eWidth).

Write a method (getPerimeter) which returns the perimeter (2 * length + 2 * width)

Write the main() function that will define an object (myRectangle) for the class, Rectangle, with the parameters (10, 20) (PYTHON)

Answers

function Rectangle(width=1, height= 1 ) {

this.width= width;

this.height= height;

this.getArea= ( ) = > {return width * height};

this.getPerimeter= ( ) = >{ return 2( height + width)};

var rectangleOne= new Rectangle(4, 40)

var rectangleTwo= new Rectangle(3.5, 35.9)

console.log(rectangleOne.width, rectangleOne.height, rectangleOne.getArea( ), rectangleOne.getPerimeter( ) )

console.log(rectangleTwo.width, rectangleTwo.height, rectangleTwo.getArea( ), rectangleTwo.getPerimeter( ) )

This is a Javascript class definition with a constructor specifying arguments with default values of one for both width and height, and the getArea and getPerimeter methods.

Learn more about Javascript on:

https://brainly.com/question/28448181

#SPJ1

Im making a hangman game on code.org for a project. Inside the onevent theres the forloop and inside the forloop theres an if statement. My problem is that when I run the program and the onevent is triggered the first part of the if statement always rings as true even when its false. Does anyone know what might be wrong with my code?

Answers

The reasons that the  if statement is not working may be due to

Syntax errorsVariable typesLogic errorsScope issues

What is the program  about?

If statement not working, one need to Check syntax and variable types. Check for logic errors when comparing different data types, as the intended comparison may not occur as expected.

Therefore, the a possible logic error causing if statement to work incorrectly. Check variable scope. Declaring a variable outside the function may make it inaccessible inside.

Learn more about program  from

https://brainly.com/question/1538272

#SPJ1

give a brief description of how you would reach as many people as possible in a report



Answers

In order to reach as many people as possible in a report, one could follow these general steps:

What are the steps?

Define the target audience: Identify who the report is intended for, and what their interests, needs, and preferences might be.

Use clear and concise language: Use language that is easy to understand, and avoid technical jargon and complex terminology.

Use visual aids: Incorporate visual aids such as graphs, charts, and images to make the report more engaging and easier to understand. Visual aids can help convey complex information quickly and effectively.

Learn more about report on

https://brainly.com/question/26177190

#SPJ1

A research organization conducts certain chemical tests on samples. They have data available on the standard results. Some of the samples give results outside the boundary of the standard results. Which data mining method follows a similar approach?
A.
data cleansing
B.
network intrusion
C.
fraud detection
D.
customer classification
E.
deviation detection

Answers

Answer:

E. deviation detection

Explanation:

got it right on plato

The max Fuel capacity a spaceship should have is 500. The minimum is 200. The ship you are designing is rated at 75% of range. How much fuel capacity does it have?

Answers

Note that where the above conditions are given, the  fuel capacity of the spaceship is somewhere between 200 and 500, but since it is rated at 75% of range, its actual fuel capacity is 225.

Why is this so ?

We know tat the spaceship is rated at 75 % of its range, but we do not know its actual range. Therefore, we cannot directly calculate its fuel capacity.

We may, however, utilize the information provided regarding the maximum and lowest fuel capacity to calculate a range of feasible fuel capacities for the spaceship.

Because the spaceship's range is rated at 75%, we may conclude that its fuel capacity is likewise within this range.

Using this logic, we can calculate the possible range of fuel capacities as follows:

Maximum fuel capacity = 500Minimum fuel capacity = 200Range of fuel capacities = Maximum - Minimum = 500 - 200 = 30075% of range = 0.75 x 300 = 225

Therefore, the fuel capacity is 225.

Learn more about fuel capacity at:

https://brainly.com/question/23186652

#SPJ1

Which option combines the selected layer with the one immediately below it, without
affecting other layers in the file?
Flatten Layers
Flatten Selected
Merge Down
Merge Visible

Answers

Answer:

The option that combines the selected layer with the one immediately below it, without affecting other layers in the file, is "Merge Down".

Explanation:

Flatten Layers combines all visible layers into a single layer, while Merge Visible combines all visible layers into a single layer, but keeps hidden layers separate. Merge Down, on the other hand, combines a selected layer with the one directly below it. So if you have Layer 1 and Layer 2 selected, Merge Down will combine Layer 2 with Layer 1. This is useful if you want to merge a specific layer with the one directly beneath it, while keeping other layers separate.

If you were to buy a used phone or laptop, what would be the most important thing you would want to check or verify before making a purchase?

Answers

Answer:

i choose quality

Explanation:

i choose the quality because for example if i want to buy a used phone first i have to know about what kind of phone i want or what is the phone quantity or quality. so if i choose the quantity may be the phone battery is dead or it has small GB, may be the phone is attaked by viruses, if the phone is older than you think. But if i choose the quality i can get what i want, the battery is not dead, the phone is not older than i think and some more advantages it gives for me.

so it means having quality is important than haveing quantity

If a form-based code is administered, then what does the administration section of the code specifically set forth? (Select all that apply.)

Responses

a description of any public elements the code impacts

a review process

an application process

a map of the area to be regulated

Answers

The administration section of a form-based code specifically shows options B and C:

a review processan application process

What is the  form-based code?

Form-based codes pertain to a form of zoning regulation that accentuates the physical aspects of the constructed world. The part of a form-based code pertaining to administration outlines the steps and prerequisites to execute the code.

The code also outlines a procedure for evaluating development proposals and a method for property owners who want to develop their land while complying with the code to submit an application.

Learn more about administration  from

https://brainly.com/question/26106218

#SPJ1

A file (data.txt) has the following data for ID, name, GPA, and hours completed

A12, ally baba, 4.00, 112
B13, scorpio beast, 3.99, 100
C15, cat animal, 2.4, 12


Write a function (getData) what will read the file and will store the data in a list of dictionaries. The first value is the key of the dictionary and the rest of the data is a list of values.

The function will return the dictionary. (PYTHON)

Answers

The get Result function reads the data file grade.txt and returns a dictionary containing the values in the file. Three key-value pairs make up the dictionary; each key is a student's name.

A built-in function in Python enables us to open files in various modes. The open() function accepts two crucial parameters: the file name and the mode; the default mode is 'r' , which opens the file for reading only.

open('grade.txt', 'r') as f: lines = f is defined in get Result().

readlines()

for line in lines: myDict =

line is equal to line.

strip()\s key, value = line.

split(',')

myDict[key] = int(value) (value)

provide myDict

To know more about function  visit:-

brainly.com/question/28939774

#SPJ1

Other Questions
researchers estimate that broad-sense heritability of iq in sweden is 0.8. which of these conclusions is valid, assuming that the estimate is accurate? please choose the correct answer from the following choices, and then select the submit answer button. answer choices most variance for iq in sweden is due to total genetic variance. enriching the environment of disadvantaged children in sweden would not lead to a big improvement in performance on iq tests. broad-sense heritability of iq in the united states probably is higher than 0.5. in sweden, the environment does not play a large role in determining the iq of individuals. Which country was a leader of the communist nations during the Cold War?Responses:United StatesVietnamSoviet UnionChina _______ is the term that denotes the ease with which people can use an interface to achieve a particular goal.A. WorkaroundB. Situational awarenessC. UsabilityD. All of these are correct. The concrete framing system for Francis Hall is most nearly described as.... Which agile methodology has as one of its core principles the concept of osmotic communication? in scramble competition polygyny males who are more persistent in searching for and finding females have what What serious conditions Chronic Abdominal pain? Kelly is currently attending a concert in a small venue where there are many people she does not know. What would be an example of the focal attention stage? a) Kelly scanning the venue automatically without conscious thought that she is doing this Ob) Kelly connecting a salient person to other people who she knows that look similar c) Kelly identifying and categorising a salient person in the venue d) Kelly elaborating on the salient person she has identified in the venue Question 2 (1 point) A company asks you to use its large database of past customers to help establish the relationship between people's preference for smartphone colours and their smartphone purchase. What study design should you consider using? a) Archival b) Correlational c) Field d) Naturalistic what is a good name for a microflow that allows you to schedule a new trainingevent from your homepage? Restex has a debt-equity ratio of0.81an equity cost of capital of18 %and a debt cost of capital of13 %Restex's corporate tax rate is38 %and its market capitalization is$ 219million.a. If Restex's free cash flow is expected to be$ 14million one year from now and will grow at a constant rate, what expected future growth rate is consistent with Restex's current market value?b. Estimate the value of Restex's interest tax shield. which statement is true about in inequality in Washington today Taxpayers who use their country club more than 50 percent for business may deduct the total amount of their membership dues.A. TrueB. False" Explain what a statistically significant outcome of an inferential statistics test tells you about the effect of the independent variable in an experiment. One of the earliest sociologists to pay close attention to status of women wasCharles H. CooleyTalcott ParsonsHarriet MartineauKarl MarxJane Addams After her initial round of treatment, what did Henrietta's doctors assume about the effectiveness of the radium therapy? The process of forming a cross wall between two daughter cells is known as _______________.A. replicationB. septationC. sporulationD. mitosis Quadrilateral DEFG is a rectangle, DH=4w+20, and GH=6w. What is GH? Exercise 8-14 Ordinary repairs, extraordinary repairs, and betterments LO C3 Oki Company pays $270.900 for equipment expected to last four years and have a $30,000 salvage value. Prepare journal entries to record the foilowing costs related to the equlpment. 1. During the second year of the equipment's life, $12.600 cash Is pald for a new component expected to Increase the equipment's productivity by 10% a year 2 During the third year, $3,150 cash is pald for normal repairs necessary to keep the equipment in good working order 3. During the fourth year, $5,550 IS pald for repairs expected to Increase the useful life of the equipment from four to five years. View transaction list Journal entry worksheet 2 Record the betterment cost of $12,600 paid in cash. Note: Enter debits before credits Transaction General Journal Debit Credit Record entry Clear entry View general jounal Oki Company pays $270,900 for equipment expected to last four years and have a $30,000 salvage valu record the following costs related to the equipment 1. During the second year of the equipment's life, $12,600 cash Is paid for a new component expected to productivity by 10% a year 2 During the third year, $3,150 cash is paid for normal repalrs necessary to keep the equipment in good w 3. During the fourth year, $5,550 IS paid for repairs expected to Increase the useful life of the equipment fr View transation list Journal entry worksheet nces < 3 1 Record the cost of normal repairs of $3,150 paid in cash to keep the equipment in good working order. Note: Enter debits before credits Transaction Debit General Journal Credit 2 Record entry Clear entry View general journal Type here to search a Exercise 8-14 Ordinary repairs, extraordinary repairs, and betterments LO Oki Company pays $270,900 for equipment expected to last four years and have a $30,000 salh record the following costs related to the equipment 1. During the second year of the equipment's life, $12,600 cash is pald for a new component exp productivity by 10% a year 2 During the third year, $3,1500 cash is paid for normal repairs necessary to keep the equipment 3. During the fourth year, $5,550 IS pald for repairs expected to Increase the useful life of the eq IS View transaction list Journal entry worksheet > 1 2 Record the cost of repairs of $5,550 paid in cash to increase the useful life of the equipment. Note: Enter debits before credits. Transaction General Journal Debit Credit 3 Record entry Clear entry View general journal Which of the following is a true statement?A. North America has fewer people than South America.OB. North America has less land area than South America.OC. North America has fewer climate zones than South America.D. North America has less income inequality than South America.SUBMIT How do you calculate semi-major axis using Kepler's third law?