Here's a sample Java program that implements the insertion sort algorithm and counts the number of comparisons and swaps performed:
import java.util.Scanner;
public class InsertionSort {
// Static variables to count the number of comparisons and swaps
static int numComparisons = 0;
static int numSwaps = 0;
public static void main(String[] args) {
// Step 1: Read the size of the array and the elements
int[] nums = readNums();
// Step 2: Print the input array
printNums(nums);
// Step 3: Perform insertion sort
insertionSort(nums);
// Step 4: Print the sorted array and the number of comparisons and swaps
printNums(nums);
System.out.printf("comparisons: %d\\", numComparisons);
System.out.printf("swaps: %d\\", numSwaps);
}
// Read and return an array of integers
// The first integer read is the number of integers that follow
static int[] readNums() {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = input.nextInt();
}
return nums;
}
// Print the numbers in the array, separated by spaces
// (No space or newline before the first number or after the last.)
static void printNums(int[] nums) {
for (int i = 0; i < nums.length; i++) {
System.out.printf("%d", nums[i]);
if (i < nums.length - 1) {
System.out.print(" ");
}
}
System.out.println();
}
// Exchange nums[j] and nums[k]
static void swap(int[] nums, int j, int k) {
int temp = nums[j];
nums[j] = nums[k];
nums[k] = temp;
}
// Perform an insertion sort on the array nums
static void insertionSort(int[] nums) {
for (int i = 1; i < nums.length; i++) {
// Insert nums[i] into the sorted subarray nums[0:i-1]
int j = i;
while (j > 0 && nums[j] < nums[j-1]) {
swap(nums, j, j-1);
numComparisons++;
numSwaps++;
j--;
}
printNums(nums); // Output the array during each iteration
numComparisons++; // Increment the number of comparisons
}
}
}