I'm struggling with the number of insertion sort key comparison and swap count..
I have this method that counts and prints out the key comparison at the end
public static void insertionSort(int[] array) {
int n = array.length;
int cm = 0;
int sw = 0;
for (int pass = 0; pass < array.length; pass++) {
// figure out what should go into a[pass]
int min = pass;
for (int j = pass + 1; j < array.length; j++) {
if (smaller(array, j, min)) {
cm++;
min = j;
}
}
swap(array, pass, min);
sw++;
}
System.out.print("Insertion sort: ");
for (int c = 0; c < n; c++) {
System.out.print(array[c] + " ");
}
System.out.println("- " + cm + " comparisons, " + sw + " swaps");
}
private static void swap(int[] a, int i, int j) {
if (i != j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
private static boolean smaller(int[] a, int i, int j) {
//another suggestion came up to call a count variable here because a false comparison could still count as a comparison
count++;
if (a[i] < a[j]) {
return true;
}
return false;
}
With this test array
int[] test = {13, 12, 5, 6, 11};
I should get 7 comparisons and 4 swaps, but I'm getting 5 comparisons and 5 swaps. With another array from 0 to 31 consequently (testing for the best case), I get 0 comparison and 32 swaps.