Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Modify the code below to count the number of comparisons and the number of swaps

ID: 3842944 • Letter: M

Question

Modify the code below to count the number of comparisons and the number of swaps

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

public class InsertionSort {
private int[] data;
private static final Random generator = new Random();

public InsertionSort( int size ) {
data = new int[ size ];

for ( int i = 0; i < size; i++ )
data[ i ] = 10 + generator.nextInt( 90 );
}

// call this method from main program
public void sort(){
int insert;

for ( int next = 1; next < data.length; next++ ) {
insert = data[ next ];
int moveItem = next;

while ( moveItem > 0 && data[ moveItem - 1 ] > insert ) {
data[ moveItem ] = data[ moveItem - 1 ];
moveItem--;
}

data[ moveItem ] = insert;
}
}
}

Explanation / Answer

Here is code:

import java.util.Arrays;
import java.util.Random;
public class InsertionSort{
private int[] data;
private static final Random generator = new Random();
public InsertionSort( int size ) {
data = new int[ size ];
for ( int i = 0; i < size; i++ )
data[ i ] = 10 + generator.nextInt( 90 );
}
// call this method from main program
public void sort(){
int insert;
int compareCounter = 0;
int swapCounter = 0;

for ( int next = 1; next < data.length; next++ ) {
insert = data[ next ];
int moveItem = next;
while ( moveItem > 0 && data[ moveItem - 1 ] > insert ) {
compareCounter++;
data[ moveItem ] = data[ moveItem - 1 ];
swapCounter++;
moveItem--;
}
// compartion for fail condition
compareCounter++;

data[ moveItem ] = insert;
}
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote