public class InsertionSort { public static void printArray(int[] a) { System.out.print("\nIndex i: "); for(int i=0; i< a.length; i++) System.out.printf("%2d, ", i); System.out.print("\nElement a[i]: "); for(int i=0; i< a.length; i++) System.out.printf("%2d, ", a[i]); System.out.println("\n\n"); } public static void main(String[] args) { int[] a= { 23, 78, 45, 8, 32, 56}; boolean DEBUG = true; // Print the unsorted array System.out.println("===== UNSORTED ARRAY ======"); printArray(a); for(int i = 1; i < a.length; i++) { int j = i; int INS = a[i]; while ((j > 0) && (a[j-1] > INS)) { a[j] = a[j-1]; // shift elements to the right j--; } a[j] = INS; // insert the element if(DEBUG) { System.out.println("===== ITERATION " + i + " ======"); printArray(a); } } // Print the sorted array System.out.println("===== SORTED ARRAY ======"); printArray(a); } }