Intertion Sort
Intertion Sort
Scanner;
// Sort numbers
/* TODO: Count comparisons and swaps. Output the array at the end of each
iteration. */
//Modification:
// Declare the countComparisons and countSwaps variable here and initialize
with zero
private static int countComparisons=0;
private static int countSwaps=0;
public static void insertionSort(int[] numbers)
{
int i;
int j;
// Modification:
// No need to declare comparison and swaps variable here
// int comparisons = 0;
// int swaps = 0;
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])
{
// Modification: declare the countComparisons here
++countComparisons;
// Swap numbers[j] and numbers[j - 1]
swap(numbers, j, j - 1);
// Modification:
// No need to declare the increment swap
// variable declare countSwaps rather than swaps
++countSwaps;
--j;
}
//Modification:
// Check the condition when j is greater than 0
if (j > 0)
// Increment count comparison
++countComparisons;
// Call here, printNums method
printNums(numbers);
}
}
//Create a main function of the program
public static void main(String[] args)
{
// Step 1: Read numbers into an array
int[] numbers = readNums();