title: How to count comparisons and swaps in insertion sort? (JAVA)
body: <pre><code>public class Sorting
  {
     public static int numOfComps = 0,
                       numOfSwaps = 0;
  
     public static void insertionSort(int[] array)
     {
        int unsortedValue;  // The first unsorted value
        int scan;           // Used to scan the array
  
        // The outer loop steps the index variable through 
        // each subscript in the array, starting at 1. The portion of
        // the array containing element 0  by itself is already sorted.
        for (int index = 1; index &lt; array.length; index++)
        {
           // The first element outside the sorted portion is
           // array[index]. Store the value of this element
           // in unsortedValue.
           unsortedValue = array[index];
  
           // Start scan at the subscript of the first element
           // outside the sorted part.
           scan = index;
  
           // Move the first element in the still unsorted part
           // into its proper position within the sorted part.
           while (scan &gt; 0 &amp;&amp; array[scan-1] &gt; unsortedValue)
           {
              array[scan] = array[scan - 1];
              scan--;
  
                  // Counts the number of values swaps
                  numOfSwaps ++;
           }
  
           // Insert the unsorted value in its proper position
           // within the sorted subset.
           array[scan] = unsortedValue;
  
           // Counts the number of values comparisons
          numOfComps ++;
        }
          System.out.println("\n\nNumber of comps = " + numOfComps);
         System.out.println("Number of swaps = " + numOfSwaps);       
     }
  }
  </code></pre>
  
  <p>Newbie here again. How do I code this insertion sort program in Java to count the number of comparisons and the number of swaps? I have inserted comparison and swap codes into the program but not sure they're in the correct place. I have posted the program. Thanks for any help. </p>