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;
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.